Posted In: JDOM XML Parser, XML

How to parse a XML String

Parsers used

1. jdom2 2.0.6
2. xerces 2.11.0
3. jaxp 1.4.2

Maven

<dependency>
	<groupId>org.jdom</groupId>
	<artifactId>jdom2</artifactId>
	<version>2.0.6</version>
</dependency>
<dependency>
	<groupId>xerces</groupId>
	<artifactId>xercesImpl</artifactId>
	<version>2.11.0</version>
</dependency>
<dependency>
	<groupId>javax.xml</groupId>
	<artifactId>jaxp-api</artifactId>
	<version>1.4.2</version>
</dependency>

 

package com.example.xml;

import java.io.IOException;
import java.io.StringReader;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.xerces.parsers.DOMParser;
import org.jdom2.Content;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Example1 {
	String xml = "<root><a><ab><ac>myval1</ac><ac>myval2</ac></ab></a></root>";

	public static void main(String[] args) {
		new Example1().jdom();
		new Example1().xerces();
		new Example1().jaxp();
	}

	public void jdom() {
		SAXBuilder saxBuilder = new SAXBuilder();
		try {
			org.jdom2.Document doc = saxBuilder.build(new StringReader(xml));
			List<Content> message = doc.getRootElement().getContent();
			for (Content c : message) {
				System.out.println(c.getValue());
			}
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void xerces() {
		DOMParser parser = new DOMParser();
		try {
			parser.parse(new InputSource(new StringReader(xml)));
			Document doc = parser.getDocument();
			String message = doc.getDocumentElement().getTextContent();
			System.out.println(message);
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void jaxp() {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = null;
		try {
			db = dbf.newDocumentBuilder();
			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xml));
			try {
				Document doc = db.parse(is);
				String message = doc.getDocumentElement().getTextContent();
				System.out.println(message);
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (ParserConfigurationException e1) {
			e1.printStackTrace();
		}
	}
}

by , on August 17th, 2017

  • Categories