Tag Archives: xml

How-to Parse an XML string in Java

Found this simple but elegant solution on the web, i am listing it here for my record, but you can also find it here – http://www.rgagnon.com/javadetails/java-0573.html

import javax.xml.parsers.*;
import org.xml.sax.InputSource;
import org.w3c.dom.*;
import java.io.*;

public class ParseXMLString {

public static void main(String arg[]) {
String xmlRecords =
“” +
” ” +
” John” +
” Manager” +
” ” +
” ” +
” Sara” +
” Clerk” +
” ” +
“”;

try {
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));

Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName(“employee”);

// iterate the employees
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);

NodeList name = element.getElementsByTagName(“name”);
Element line = (Element) name.item(0);
System.out.println(“Name: ” + getCharacterDataFromElement(line));

NodeList title = element.getElementsByTagName(“title”);
line = (Element) title.item(0);
System.out.println(“Title: ” + getCharacterDataFromElement(line));
}
}
catch (Exception e) {
e.printStackTrace();
}
/*
output :
Name: John
Title: Manager
Name: Sara
Title: Clerk
*/

}

public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return “?”;
}
}

Advertisements

Leave a comment

Filed under Java, XML