有人能找出这段代码有什么问题吗?无论我选择什么 XPath,它总是返回空字符串
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("chart.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
String str = (String) xpath.evaluate("/row[@id='1']", doc.getDocumentElement(), XPathConstants.STRING);
System.out.println("xml string is"+str);
我的chart.xml是
<?xml version="1.0" encoding="iso-8859-1"?>
<chart>
<row id="1">
<Select numofobjects="0" id="1000" index="1">
<Table alias="ConvertDetails" name="ConvertDetails"/>
</Select>
</row>
<row id="2">
<Select numofobjects="0" id="2000" index="2">
<Table alias="ConvertDetails" name="ConvertDetails"/>
</Select>
</row>
</chart>
我的预期输出是
<Select numofobjects="0" id="1000" index="1">
<Table alias="ConvertDetails" name="ConvertDetails"/>
</Select>
最佳答案
正如 Martin 指出的,您需要选择一个节点,而不是它的字符串值:
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("chart.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
Node n = (Node) xpath.evaluate("row[@id='1']", doc.getDocumentElement(),
XPathConstants.NODE);
然后您可以使用以下序列化辅助方法(借自 Get a node's inner XML as String in Java DOM ):
public static String innerXml(Node node) {
DOMImplementationLS lsImpl = (DOMImplementationLS)node.getOwnerDocument()
.getImplementation()
.getFeature("LS", "3.0");
LSSerializer lsSerializer = lsImpl.createLSSerializer();
lsSerializer.getDomConfig().setParameter("xml-declaration", false);
NodeList childNodes = node.getChildNodes();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < childNodes.getLength(); i++) {
sb.append(lsSerializer.writeToString(childNodes.item(i)));
}
return sb.toString();
}
像这样:
String xmlStr = "";
if (n != null) {
xmlStr = innerXml(node);
}
关于java - 陷入 java XPath 困境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27423109/