Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to parse an XML String in Java?

Tags:

java

xml

I am parsing a string in Java using javax.xml.parsers.DocumentBuilder. However, there is not a function to parse a String directly, so I am instead doing this:

public static Document parseText(String zText) {
    try
    {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(new InputSource(new StringReader(zText)));
        doc.getDocumentElement().normalize();
        return doc;
    }
    catch (Exception e) {
            e.printStackTrace();
    }
    return null;
}

Is this the best way to do it? I feel like there must be a simpler way... thanks!

like image 997
Soren Johnson Avatar asked Jan 24 '23 03:01

Soren Johnson


1 Answers

To answer your question directly - to my knowledge, there is not a better way. The input source is used because it is more universal and can handle input from a file, a String or across the wire is my understanding.

You could also try using the SAX Xml parser - it is a little more basic, and uses the Visitor Pattern, but it gets the job done and for smallish data sets and simple XML schemas it is pretty easy to use. SAX is also included with the core JRE.

like image 193
aperkins Avatar answered Feb 01 '23 10:02

aperkins