我有一些包含XML的小字符串,例如:
String myxml = "<resp><status>good</status><msg>hi</msg></resp>";
我想查询它们的内容,最简单的方法是什么?使用Java 1.5及以上版本,无需外部依赖即可使用XPath:
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);
使用dom4j,类似于McDowell的解决方案:
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);
@这个答案的评论:
您可以创建一个方法,使其看起来更简单。
String xml = "<resp><status>good</status><msg>hi</msg></resp>";
System.out.printf("satus= %s\n", getValue("/resp/status", xml ) );
public String getValue( String path, String xml ) {
return XPathFactory
.newInstance()
.newXPath()
.evaluate( path , new InputSource(
new StringReader(xml)));
}
如果你已经掌握了在Java中查询XML的简单方法,请看一下XOM。
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);
}
这里是一个查询你的 XML 的代码片段,使用 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();
vg.setDoc(myXML.getBytes());
vg.parse(false);
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("/resp/status");
int i = ap.evalXPath();
if (i!=-1)
System.out.println(" result ==>"+vn.toString(i));
}
}