Simplest way to query XML in Java
Solution 1:
XPath using Java 1.5 and above, without external 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);
Solution 2:
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 simpler using dom4j. And several other comparable XML libraries exist. Alternatives to dom4j are discussed here.
Solution 3:
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");
System.out.println(nodes.get(0).getValue());
I like XOM more than dom4j for its simplicity and correctness. XOM won't let you create invalid XML even if you want to ;-) (e.g. with illegal characters in character data)