我正在構建一個應用程式,該應用程式將從用戶那里獲取一個單詞,然后使用 XPath 掃描檔案,回傳 true 或 false,具體取決于該單詞是否在該檔案中找到。
我已經構建了以下實作 XPath 的類,但我要么誤解了它應該如何作業,要么我的代碼有問題。誰能向我解釋如何使用 Xpath 進行完整檔案搜索?
public XPath() throws IOException, SAXException, ParserConfigurationException, XPathExpressionException {
FileInputStream fileIS = new FileInputStream("text.xml");
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(fileIS);
XPathFactory xPathfactory = XPathFactory.newInstance();
javax.xml.xpath.XPath xPath = xPathfactory.newXPath();
XPathExpression expr = xPath.compile("//text()[contains(.,'java')]");
System.out.println(expr.evaluate(xmlDocument, XPathConstants.NODESET));
}
以及我目前正在測驗的 xml 檔案。
<?xml version="1.0"?>
<Tutorials>
<Tutorial tutId="01" type="java">
<title>Guava</title>
<description>Introduction to Guava</description>
<date>04/04/2016</date>
<author>GuavaAuthor</author>
</Tutorial>
<Tutorial tutId="02" type="java">
<title>XML</title>
<description>Introduction to XPath</description>
<date>04/05/2016</date>
<author>XMLAuthor</author>
</Tutorial>
</Tutorials>
找到了解決方案,我錯過了找到的條目的正確顯示,正如有人在評論“java”中指出的那樣,我只想掃描文本欄位,因此在添加以下代碼并更改單詞 my 后,它永遠不會被找到應用程式將尋找,應用程式作業
Object result = expr.evaluate(xmlDocument, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i ) {
System.out.println(nodes.item(i).getNodeValue());
}
uj5u.com熱心網友回復:
您的 XPath 正在搜索text()節點,但該詞java出現在@type屬性(不是text()節點)中。
如果你想在兩者中搜索這個詞text(),@*然后你可以使用聯合|運算子并檢查包含該詞的其中一個/兩個:
//text()[contains(. ,'java')] | //@*[contains(., 'java')]
但是您可能還想掃描comment()and processing-instruction(),因此可以node()在謂詞測驗中一般匹配 on和 then :
//node()[contains(. ,'java')] | //@*[contains(., 'java')]
使用 XPath 2.0 或更高版本,您可以使用:
//node()[(.|@*)[contains(., 'java')]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/375484.html
