Java – Simplest way to query XML in Java


I have small Strings with XML, like:

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

which I want to query to get their content.

What would be the simplest way to do this?

Best Solution

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);