![](/img/trans.png)
[英]How to extract element value from an xml containing namespaces with xPath in Java?
[英]Java xPath - extract subdocument from XML
我有一個XML文檔,如下所示:
<DocumentWrapper>
<DocumentHeader>
...
</DocumentHeader>
<DocumentBody>
<Invoice>
<Buyer/>
<Seller/>
</Invoice>
</DocumentBody>
</DocumentWrapper>
我想從中提取DocumentBody元素的內容為String,原始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);
調用此方法
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.