tags:

views:

306

answers:

3

What is the fastest method(fastest performing) to parse an xml that is in a string, in Java platform ?

The file size can be around say 25kb.

The constraint is that I am not presented with an xml file, rather I have to parse the xml string !!

+2  A: 

Generally, you have three options: DOM, SAX and StAX. DOM is slower.

StAX is said to provide "DOM ease with SAX efficiency". But in case the document you showed is the whole document - it really doesn't matter. The performance differences are important when working with larger files.

Bozho
+2  A: 

You should apply to your case general concepts from parsing theory.

An explanation of complexity of the main parsing techniques is available in this article.

Regarding Java, here is a comparison among XML parser in Java by Sun, Oracle and Apache.

Reading from the abstract of the article:

he XML parser world is a dynamic one. As standards change, the parsers change as well--XML parsers are becoming more sophisticated. For most programming projects, the parser, at minimum, must support DOM Level 2, SAX 2, XSLT, and Namespaces. All the parsers discussed here provide these capabilities; however, there are distinct differences in performance, reliability, and conformance to standards. In this article, I'll compare the latest parsers from Sun, Oracle, and the Apache Software Foundation.

The rest of the analysis is available here.

Roberto Aloi
+3  A: 

You could build a DOM tree with the parsing result of your XML string. Here is a Java method to accomplish what you want:

private static Document ParseXMLString(String xmlString) {
    try {
        DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = fac.newDocumentBuilder();
        InputSource inStream = new InputSource();
        inStream.setCharacterStream(new StringReader(xmlString));
        Document doc = db.parse(inStream);
        return doc;
    }
    catch (Exception e) {
        System.out.println(e);
    }
}
XpiritO