I have small Strings with XML, like:
String myxml = \"good hi \";
<
You could try JXPath
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);
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.
@The comments of this answer:
You can create a 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
.newInstance()
.newXPath()
.evaluate( path , new InputSource(
new StringReader(xml)));
}
After your done with simple ways to query XML in java. Look at XOM.
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)