【发布时间】:2009-04-30 15:11:12
【问题描述】:
我有带有 XML 的小字符串,例如:
String myxml = "<resp><status>good</status><msg>hi</msg></resp>";
我想查询它以获取他们的内容。
最简单的方法是什么?
【问题讨论】:
我有带有 XML 的小字符串,例如:
String myxml = "<resp><status>good</status><msg>hi</msg></resp>";
我想查询它以获取他们的内容。
最简单的方法是什么?
【问题讨论】:
XPath 使用 Java 1.5 及以上版本,无外部依赖:
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'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);
使用 dom4j 处理 XML 稍微简单一些。以及其他几个类似的 XML 库exist。 dom4j 的替代品是discussed here。
【讨论】:
这是如何使用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());
比起 dom4j,我更喜欢 XOM,因为它的 simplicity and correctness。 XOM 不会让您创建无效的 XML,即使您想这样做 ;-)(例如,在字符数据中使用非法字符)
【讨论】:
你可以试试JXPath
【讨论】:
在你用简单的方法在 java 中查询 XML 之后。看看 XOM。
【讨论】:
@这个answer的cmets:
你可以创建一个方法让它看起来更简单
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)));
}
【讨论】:
将此字符串转换为 DOM 对象并访问节点:
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);
}
【讨论】:
这是使用VTD-XML查询您的XML的代码sn-p
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));
}
}
【讨论】:
您可以使用Jerry 来查询类似于jQuery 的XML。
jerry(myxml).$("status")
【讨论】: