【问题标题】:Java xPath - extract subdocument from XMLJava xPath - 从 XML 中提取子文档
【发布时间】:2012-11-04 09:21:44
【问题描述】:

我有一个如下的 XML 文档:

<DocumentWrapper>
  <DocumentHeader>
    ...
  </DocumentHeader>
  <DocumentBody>
    <Invoice>
      <Buyer/>
      <Seller/>
    </Invoice>
   </DocumentBody>
 </DocumentWrapper>

我想从中提取 DocumentBody 元素的内容作为字符串,原始 XML 文档:

<Invoice>
  <Buyer/>
  <Seller/>
</Invoice>

使用 xPath 可以很容易地获得:

/DocumentWrapper/DocumentBody

不幸的是,我的 Java 代码无法按我的意愿工作。它返回空行而不是预期结果。有没有机会这样做,或者我必须返回 NodeList 然后从中生成 xml 文档?

我的 Java 代码:

XPathFactory xPathFactoryXPathFactory.newInstance();
XPath xPath xPathFactory.newXPath();
XPathExpression xPath.compile(xPathQuery);

String result = expression.evaluate(xmlDocument);

【问题讨论】:

    标签: java xml xpath extract


    【解决方案1】:

    调用这个方法

    String result = expression.evaluate(xmlDocument);
    

    和调用这个是一样的

    String result = (String) expression.evaluate(xmlDocument, XPathConstants.STRING);
    

    返回结果节点的字符数据,如果结果节点是元素,则返回所有子节点的字符数据。

    你可能应该这样做:

    Node result = (Node) expression.evaluate(xmlDocument, XPathConstants.NODE);
    TransformerFactory.newInstance().newTransformer()
                .transform(new DOMSource(result), new StreamResult(System.out));
    

    【讨论】:

    • XMLConstants.NODE 看起来不再有效。
    • @takias 真的! XMLConstants -> XPathConstants
    猜你喜欢
    • 1970-01-01
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    相关资源
    最近更新 更多