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?
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?
convert this string into a DOM object and 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);
}
XPath in Java 1.5 and above:
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);
After your done with simple ways to query XML in java. Look at XOM.
Using a library such as dom4j:
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);
This does the same as McDowell's solution (sans the typo :).
dom4j has its warts, but I think it makes XML handling in Java easier. (Several other comparable XML libraries exist, see e.g. this question. Edit: Also, for my quest to find the best alternative to dom4j, see: What Java XML library do you recommend (to replace dom4j)?.)
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)
@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)));
}