<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Java XPath 示例 – XPath 教程 > 原文: [https://howtodoinjava.com/xml/java-xpath-tutorial-example/](https://howtodoinjava.com/xml/java-xpath-tutorial-example/) 在此 **Java XPath 教程**中,我們將學習什么是 **XPath 庫**,什么是 XPath 數據類型,并學習創建 XPath 表達式語法以從 XML 文件或文檔中檢索信息。 此信息可以是 XML 節點或 XML 屬性,甚至可以是注釋。 ```java Table of Contents 1\. What is XPath? 2\. XPath Data Model 3\. XPath Data Types 4\. XPath Syntax 5\. XPath Expressions 6\. Recommended reading ``` 在本教程中,我們將在運行各種 **XPath 示例**時使用此 XML。 ```java <?xml version="1.0" encoding="utf-8" ?> <inventory> <!--Test is test comment--> <book year="2000"> <title>Snow Crash</title> <author>Neal Stephenson</author> <publisher>Spectra</publisher> <isbn>0553380958</isbn> <price>14.95</price> </book> <book year="2005"> <title>Burning Tower</title> <author>Larry Niven</author> <author>Jerry Pournelle</author> <publisher>Pocket</publisher> <isbn>0743416910</isbn> <price>5.99</price> </book> <book year="1995"> <title>Zodiac</title> <author>Neal Stephenson</author> <publisher>Spectra</publisher> <isbn>0553573862</isbn> <price>7.50</price> </book> </inventory> ``` ## 1.什么是 XPath [**XPath**](https://en.wikipedia.org/wiki/XPath "XPath") 是一種語法,用于描述 [XML](https://en.wikipedia.org/wiki/XML "XML") 文檔的各個部分。 使用 XPath,您可以引用第一個元素,元素的任何屬性,包含某些文本的所有特定元素以及許多其他變體。 [XSLT](https://en.wikipedia.org/wiki/XSLT "XSLT") 樣式表在匹配項中使用 XPath 表達式,并選擇各種元素的屬性來指示應如何轉換文檔。 在使用 XML 發送請求和接收響應來測試 [Web 服務](https://en.wikipedia.org/wiki/Web_service "Web services")時,XPath 有時會很有用。 XPath 使用的語言語法與我們已經知道的非常相似。 語法是基本編程語言表達式(例如`$x*6`的通配符)和**類 Unix 路徑表達式**(例如`/inventory/author`)的混合。 除了基本語法外,XPath 還提供了一組有用的函數(例如`count()`或`contains()`,與工具函數調用非常相似),這些函數使您可以搜索文檔中的各種數據片段。 ## 2\. XPath 數據模型 XPath 將 XML 文檔視為節點的[樹](https://en.wikipedia.org/wiki/Tree_%28data_structure%29 "tree")。 該樹與[文檔對象模型](https://www.w3.org/DOM/ "DOM")(即 DOM 樹)非常相似,因此,如果您熟悉 DOM,則可以輕松了解如何構建基本的 **XPath 表達式**。 XPath 數據模型中有七種節點: 1. 根節點(每個文檔僅一個) 2. 元素節點 3. 屬性節點 4. 文本節點 5. 注釋節點 6. 處理指令節點 7. 命名空間節點 #### 2.1 根節點 [根節點](https://en.wikipedia.org/wiki/Root_element "root node")是包含整個文檔的 XPath 節點。 在我們的示例中,根節點包含`<inventory>`元素。 在 XPath 表達式中,用單斜杠(`'/'`)指定根節點。 #### 2.2 元素節點 原始 XML 文檔中的每個元素都由一個 XPath 元素節點表示。 例如,在下面的示例 XML 中,是元素節點。 * `book` * `title` * `author` * `publisher` * `isbn` * `price` #### 2.3 屬性節點 元素節點至少是 XML 源文檔中每個屬性的一個屬性節點的父級。 **這些節點用于定義有關特定元素節點**的特征。 例如,在我們的 XML 片段“`year`”中是一個屬性節點。 #### 2.4 文本節點 文本節點非常簡單。 **它們包含來自元素**的文本。 如果 XML 文檔中的原始文本包含實體或字符引用,則在創建 XPath 文本節點之前將其解析。 文本節點是純凈的文本。 文本節點需要包含盡可能多的文本。 *請記住,文本節點的下一個或上一個節點不能是另一個文本節點。* 例如,我們 XML 片段中的所有值都是文本節點,例如 “`Snow Crash`”和“`Neal Stephenson`”。 #### 2.5 注釋節點 注釋節點也非常簡單 - 它包含一些文本。 **源文檔中的每個注釋都將成為注釋節點**。 注釋節點的文本包含注釋中的所有內容,除了`<!--`開頭和`-->`結尾。 例如: ```java <!--Test is test comment--> ``` #### 2.6 處理指令節點 **處理指令節點具有兩個部分**,**名稱**(由`name()`函數返回)和**字符串值**。 字符串值是名稱`<?xml`之后的所有內容,包括空格,但不包括關閉處理指令的`?>`。 例如: ```java <?xml version="1.0" encoding="utf-8"?> ``` #### 2.7 命名空間節點 XSLT 樣式表幾乎從未使用過命名空間節點。 **它們的存在主要是為了 XSLT 處理器的利益**。 > 請記住,即使從技術上來說,命名空間的聲明(例如 `xmlns:auth="http://www.authors.net"`)在 XML 源中仍是一個屬性,但它成為命名空間節點,而不是屬性節點。 ## 3\. XPath 數據類型 在 Java 中,XPath 表達式可能返回以下數據類型之一: 1. [**節點集**](https://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/xpath/XPathConstants.html#NODESET "NODESET") – 表示一組節點。 該集合可以為空,也可以包含任意數量的節點。 2. [**節點**](https://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/xpath/XPathConstants.html#NODE "NODE") (Java 支持)– 表示單個節點。 它可以為空,也可以包含任意數量的子節點。 3. [**布爾值**](https://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/xpath/XPathConstants.html#BOOLEAN "BOOLEAN") – 表示值`true`或`false`。 請注意,在 XPath 中,`true`或`false`字符串沒有特殊含義或值。 有關布爾值的更詳細討論,請參見第 4 章的 4.2.1.2 節。 4. [**數字**](https://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/xpath/XPathConstants.html#NUMBER "NUMBER") – 表示浮點數。 XPath 和 XSLT 中的所有數字均實現為浮點數; XPath 和 XSLT 中不存在整數(或`int`)數據類型。 具體來說,所有數字都實現為 IEEE 754 浮點數,與 Java `float`和`double`原始類型使用的標準相同。 除普通數字外,數字還有五個特殊值:正負無窮大,正負零和`NaN`(非數字的特殊符號)。 5. [**字符串**](https://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/xpath/XPathConstants.html#STRING "STRING") – 表示零個或多個字符,如 XML 規范中所定義。 這些數據類型通常很簡單,并且除了節點集之外,類型之間的轉換通常很簡單。 我們將不在這里更詳細地討論這些數據類型。 相反,我們將討論數據類型和轉換,因為我們需要它們來執行特定的任務。 ## 4\. XPath 語法 XPath 使用 UNIX 和[正則表達式](https://en.wikipedia.org/wiki/Regular_expression "Regular expression")這種語法。 #### 4.1 選擇具有 xpath 的節點 | 表達式 | 描述 | | --- | --- | | `nodename` | 選擇所有名稱為“`nodename`”的節點 | | `/` | 從根節點選擇 | | `//` | 從當前節點中選擇匹配選擇的節點,無論它們在何處 | | `.` | 選擇當前節點 | | `..` | 選擇當前節點的父節點 | | `@` | 選擇屬性 | #### 4.2 將謂詞與 xpath 一起使用 **謂詞用于查找特定節點或包含特定值的節點。** *謂詞始終嵌入在方括號中。* 我們將在下一節中學習如何使用它們。 #### 4.3 使用 xpath 訪問未知節點 **XPath 通配符**可用于選擇未知的 XML 元素。 | 通配符 | 描述 | | --- | --- | | `*` | 匹配任何元素節點 | | `@*` | 匹配任何屬性節點 | | `node()` | 匹配任何種類的任何節點 | #### 4.4 XPath 軸 [軸](https://www.w3schools.com/xsl/xpath_axes.asp "xpath axis")定義相對于當前節點的節點集。 以下是默認定義的軸。 | 軸名 | 結果 | | --- | --- | | `ancestor` | 選擇當前節點的所有祖先(父,祖父等) | | `ancestor-or-self` | 選擇當前節點的所有祖先(父,祖父等)和當前節點本身 | | `attribute` | 選擇當前節點的所有屬性 | | `child` | 選擇當前節點的所有子節點 | | `descendant` | 選擇當前節點的所有后代(子代,孫代等) | | `descendant-or-self` | 選擇當前節點的所有后代(子代,孫代等)和當前節點本身 | | `following` | 選擇當前節點的結束標記之后的文檔中的所有內容 | | `following-sibling` | 選擇當前節點之后的所有同級 | | `namespace` | 選擇當前節點的所有命名空間節點 | | `parent` | 選擇當前節點的父節點 | | `preceding` | 選擇出現在文檔中當前節點之前的所有節點,但祖先,屬性節點和命名空間節點除外 | | `preceding-sibling` | 選擇當前節點之前的所有同級 | | `self` | 選擇當前節點 | #### 4.5 XPath 運算符 以下是可在 XPath 表達式中使用的 **xpath 運算符**的列表: | 運算符 | 描述 | 例 | 返回值 | | --- | --- | --- | --- | | <code>&#124;</code> | 計算兩個節點集 | <code>//book &#124; //cd</code> | 返回包含所有`book`和`cd`元素的節點集 | | `+` | 加法 | `6 + 4` | 10 | | `-` | 減法 | `6 – 4` | 2 | | `*` | 乘法 | `6 * 4` | 24 | | `div` | 除法 | `8 div 4` | 2 | | `=` | 等于 | `price = 9.80` | 如果價格為 9.80,則為`true`,如果價格為 9.90,則為`false` | | `!=` | 不等于 | `price != 9.80` | 如果價格為 9.90,則為`true`,如果價格為 9.80,則為`false` | | `<` | 小于 | `price < 9.80` | 如果價格為 9.00,則為`true`,如果價格為 9.80,則為`false` | | `< =` | 小于或等于 | `price <= 9.80` | 如果價格為 9.00,則為`true`,如果價格為 9.90,則為`false` | | `>` | 大于 | `prcie > 9.80` | 如果價格為 9.90,則為`true`,如果價格為 9.80,則為`false` | | `>=` | 大于或等于 | `price >= 9.80` | 如果價格為 9.90,則為`true`,如果價格為 9.70,則為`false` | | `or` | 或 | `price = 9.80 or price = 9.70` | 如果價格為 9.80,則為`true`,如果價格為 9.50,則為`false` | | `and` | 且 | `price > 9.00 and price < 9.90` | 如果價格為 9.80,則為`true`,如果價格為 8.50,則為`false` | | `mod` | 模數(除法余數) | `5 mod 2` | 1 | ## 5\. XPath 表達式 讓我們嘗試使用 XPath 表達式和給定的數據類型來檢索 XML 的不同部分。 ```java package xml; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; public class XPathTest { public static void main(String[] args) throws Exception { //Build DOM DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // never forget this! DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse("inventory.xml"); //Create XPath XPathFactory xpathfactory = XPathFactory.newInstance(); XPath xpath = xpathfactory.newXPath(); System.out.println("n//1) Get book titles written after 2001"); // 1) Get book titles written after 2001 XPathExpression expr = xpath.compile("//book[@year>2001]/title/text()"); Object 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()); } System.out.println("n//2) Get book titles written before 2001"); // 2) Get book titles written before 2001 expr = xpath.compile("//book[@year<2001]/title/text()"); result = expr.evaluate(doc, XPathConstants.NODESET); nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i).getNodeValue()); } System.out.println("n//3) Get book titles cheaper than 8 dollars"); // 3) Get book titles cheaper than 8 dollars expr = xpath.compile("//book[price<8]/title/text()"); result = expr.evaluate(doc, XPathConstants.NODESET); nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i).getNodeValue()); } System.out.println("n//4) Get book titles costlier than 8 dollars"); // 4) Get book titles costlier than 8 dollars expr = xpath.compile("//book[price>8]/title/text()"); result = expr.evaluate(doc, XPathConstants.NODESET); nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i).getNodeValue()); } System.out.println("n//5) Get book titles added in first node"); // 5) Get book titles added in first node expr = xpath.compile("//book[1]/title/text()"); result = expr.evaluate(doc, XPathConstants.NODESET); nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i).getNodeValue()); } System.out.println("n//6) Get book title added in last node"); // 6) Get book title added in last node expr = xpath.compile("//book[last()]/title/text()"); result = expr.evaluate(doc, XPathConstants.NODESET); nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i).getNodeValue()); } System.out.println("n//7) Get all writers"); // 7) Get all writers expr = xpath.compile("//book/author/text()"); result = expr.evaluate(doc, XPathConstants.NODESET); nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i).getNodeValue()); } System.out.println("n//8) Count all books titles "); // 8) Count all books titles expr = xpath.compile("count(//book/title)"); result = expr.evaluate(doc, XPathConstants.NUMBER); Double count = (Double) result; System.out.println(count.intValue()); System.out.println("n//9) Get book titles with writer name start with Neal"); // 9) Get book titles with writer name start with Neal expr = xpath.compile("//book[starts-with(author,'Neal')]"); result = expr.evaluate(doc, XPathConstants.NODESET); nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i) .getChildNodes() .item(1) //node <title> is on first index .getTextContent()); } System.out.println("n//10) Get book titles with writer name containing Niven"); // 10) Get book titles with writer name containing Niven expr = xpath.compile("//book[contains(author,'Niven')]"); result = expr.evaluate(doc, XPathConstants.NODESET); nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i) .getChildNodes() .item(1) //node <title> is on first index .getTextContent()); } System.out.println("//11) Get book titles written by Neal Stephenson"); // 11) Get book titles written by Neal Stephenson expr = xpath.compile("//book[author='Neal Stephenson']/title/text()"); result = expr.evaluate(doc, XPathConstants.NODESET); nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i).getNodeValue()); } System.out.println("n//12) Get count of book titles written by Neal Stephenson"); // 12) Get count of book titles written by Neal Stephenson expr = xpath.compile("count(//book[author='Neal Stephenson'])"); result = expr.evaluate(doc, XPathConstants.NUMBER); count = (Double) result; System.out.println(count.intValue()); System.out.println("n//13) Reading comment node "); // 13) Reading comment node expr = xpath.compile("//inventory/comment()"); result = expr.evaluate(doc, XPathConstants.STRING); String comment = (String) result; System.out.println(comment); } } ``` 程序輸出: ```java //1) Get book titles written after 2001 Burning Tower //2) Get book titles written before 2001 Snow Crash Zodiac //3) Get book titles cheaper than 8 dollars Burning Tower Zodiac //4) Get book titles costlier than 8 dollars Snow Crash //5) Get book titles added in the first node Snow Crash //6) Get book title added in last node Zodiac //7) Get all writers Neal Stephenson Larry Niven Jerry Pournelle Neal Stephenson //8) Count all books titles 3 //9) Get book titles with writer name start with Neal Snow Crash Zodiac //10) Get book titles with writer name containing Niven Burning Tower //11) Get book titles written by Neal Stephenson Snow Crash Zodiac //12) Get count of book titles written by Neal Stephenson 2 //13) Reading comment node Test is test comment ``` 希望本 xpath 教程對您有所幫助。 它將幫助您使用 Java 執行 **xpath**。 字符串的 **Java xpath 示例**也將在 **Java8** 中成功運行。 如果您有任何建議,請發表評論。 學習愉快! 推薦閱讀: [http://www.w3.org/TR/xpath-full-text-10-use-cases](https://www.w3.org/TR/xpath-full-text-10-use-cases/ "xpath use cases") [http://en.wikipedia.org/wiki/XPath](https://en.wikipedia.org/wiki/XPath "wiki link") [http://oreilly.com/catalog/xmlnut/chapter/ch09.html](https://oreilly.com/catalog/xmlnut/chapter/ch09.html)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看