[ACCEPTED]-Simplest way to query XML in Java-xml

Accepted answer
Score: 38

XPath using Java 1.5 and above, without external 1 dependencies:

String xml = "<resp><status>good</status><msg>hi</msg></resp>";

XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();

InputSource source = new InputSource(new StringReader(xml));
String status = xpath.evaluate("/resp/status", source);

System.out.println("satus=" + status);
Score: 7

Using dom4j, similar to McDowell's solution:

String myxml = "<resp><status>good</status><msg>hi</msg></resp>";

Document document = new SAXReader().read(new StringReader(myxml));
String status = document.valueOf("/resp/msg");

System.out.println("status = " + status);

XML handling is a bit 3 simpler using dom4j. And several other comparable 2 XML libraries exist. Alternatives to dom4j are 1 discussed here.

Score: 6

Here is example of how to do that with XOM:

String myxml = "<resp><status>good</status><msg>hi</msg></resp>";

Document document = new Builder().build(myxml, "test.xml");
Nodes nodes = document.query("/resp/status");


I 4 like XOM more than dom4j for its simplicity and correctness. XOM won't 3 let you create invalid XML even if you want 2 to ;-) (e.g. with illegal characters in 1 character data)

Score: 2

You could try JXPath


Score: 2

After your done with simple ways to query 1 XML in java. Look at XOM.

Score: 2

@The comments of this answer:

You can create a 1 method to make it look simpler

String xml = "<resp><status>good</status><msg>hi</msg></resp>";

System.out.printf("satus= %s\n", getValue("/resp/status", xml ) );

The implementation:

public String getValue( String path, String xml ) { 
    return XPathFactory
               .evaluate( path , new InputSource(
                                 new StringReader(xml)));

Score: 1

convert this string into a DOM object and 1 visit the nodes:

Document dom= DocumentBuilderFactory().newDocumentBuilder().parse(new InputSource(new StringReader(myxml)));
Element root= dom.getDocumentElement();
for(Node n=root.getFirstChild();n!=null;n=n.getNextSibling())
 System.err.prinlnt("Current node is:"+n);
Score: 0

Here is a code snippet of querying your 1 XML with VTD-XML

import com.ximpleware.*;
public class simpleQuery {

    public static void main(String[] s) throws Exception{
        String myXML="<resp><status>good</status><msg>hi</msg></resp>";
        VTDGen vg = new VTDGen();
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        int i = ap.evalXPath();
        if (i!=-1)
            System.out.println(" result ==>"+vn.toString(i));
Score: 0

You can use Jerry to query XML similar to jQuery.



More Related questions