java - 陷入 java XPath 困境

标签 java xml xpath

有人能找出这段代码有什么问题吗?无论我选择什么 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/

相关文章:

java - 店铺搜索

java - 无法在开发模式下使用 GWT

java - 如何在 hibernate 中映射自动增量字段?

CSS 选择器如何获取特定元素的索引

xslt - XSLT:测试节点是否存在,无论它是当前节点的子代还是子代

c - Webkit webkit_dom_document_evaluate 函数文档

java - 错误 400 : Bad Request involving Timestamp within JSON object

java - 使用 fused Location Provider 获取当前位置

java - 当我尝试从 GitHub 存储库构建和运行代码时出现 Gradle 同步问题

c# - 读取xml时应该什么时候使用xml schemas(.xsd)?