2

次のような 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);
4

1 に答える 1

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));
于 2012-11-04T15:44:19.773 に答える