[英]xpath in java to extract all the xml elements
任何人都可以提供一個示例,使用 java 中的 xpath 從 xml 文件中提取所有元素及其屬性和值嗎?
謝謝
幾年前我為我的團隊寫了這篇文章。 會有幫助的。
XPath中有七種節點:元素節點、屬性節點、文本節點、名稱空間節點、處理指令節點、注釋節點和文檔(根)節點。 XML 文檔被視為節點樹。 樹的根稱為文檔節點(或根節點)。
考慮以下 Xml 文檔。
<information>
<person id="1">
<name>Tito George</name>
<age>25</age>
<gender>Male</gender>
<dob>
<date>25</date>
<month>october</month>
<year>1983</year>
</dob>
</person>
<person id="2">
<name>Kumar</name>
<age>32</age>
<gender>Male</gender>
<dob>
<date>28</date>
<month>january</month>
<year>1975</year>
</dob>
</person>
<person id="3">
<name>Deepali</name>
<age>25</age>
<gender>Female</gender>
<dob>
<date>17</date>
<month>january</month>
<year>1988</year>
</dob>
</person>
</information>
從文檔中獲取信息
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
//Getting the instance of DocumentBuilderFactory
domFactory.setNamespaceAware(true);
//true if the parser produced will provide support for XML namespaces;
DocumentBuilder builder = domFactory.newDocumentBuilder();
//Creating document builder
Document doc = builder.parse("C:\\JavaTestFiles\\persons.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
//getting instance of xPath
expr = xpath.compile("//@id");
result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
上面紅色的那一行是用於編譯 xPath 表達式的那一行, //@id 是實際的表達式。 表達式 //@id 將返回文檔中屬性 id 的值。 IE。 程序的輸出將是 1 2 和 3。在下表中,您可以找到可以在本文檔中使用的各種表達式。
上面代碼片段中的兩個重要語句是
基本上: XML 文檔是一個樹狀結構(分層)節點集合。 與分層目錄結構一樣,指定指向層次結構中特定節點的路徑很有用(因此規范的名稱:XPath)。
事實上,目錄路徑的大部分符號都原封不動地保留下來:
以這種方式使用這個 XPath 表達式"//*"
Document doc = ... // the document on which apply XPath
XPathExpression xp = XPathFactory.newInstance().newXPath().compile("//*");
NodeList elements = (NodeList) xp.evaluate(doc, XPathConstants.NODESET);
它返回給您任何級別的所有元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.