Thursday, July 14, 2011

Parse XML String in Java

Here are a couple of easy ways to parse an xml string in java:

String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><string xmlns=\"http://playingtreee.blogspot.com/\">4654ebd75e9cbd8a4823e964f0dceef0</string>";

Example 1:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));
System.out.println(doc.getFirstChild().getTextContent());

Example 2:

DOMParser parser = new DOMParser();
parser.parse(new InputSource(new StringReader(xml))); 

Document doc = parser.getDocument();
System.out.println(doc.getFirstChild().getTextContent());

No comments:

Post a Comment