在Java中使用xpath對xml解析,javaxpathxml解析

來源:互聯網
上載者:User

在Java中使用xpath對xml解析,javaxpathxml解析

xpath是一門在xml文檔中尋找資訊的語言。xpath用於在XML文檔中通過元素和屬性進行導航。它的傳回值可能是節點,節點集合,文本,以及節點和文本的混合等。
在學習本文檔之前應該對XML的節點,元素,屬性,文本,處理指示,注釋,根節點,命名空間以及節點關係有一定的瞭解以及對xpath也有瞭解。
XML學習地址:http://www.runoob.com/xml/xml-tutorial.html
xpath基本文法學習地址:http://www.runoob.com/xpath/xpath-tutorial.html
xpath官方文檔:https://yunpan.cn/cvc4tEIGy5EvS 訪問密碼 9d16
本文主要介紹:Java中使用xpath操作對xml操作。
1)首先在dom4j中如何使用xpath技術
匯入xPath支援的jar包。jaxen-1.1-beta-6.jar(首先要先匯入dom4j包,dom4j:http://www.dom4j.org/dom4j-1.6.1/)。

導包之後:

如果不知道怎樣導包請參考我以前的一篇部落格:Java擷取xml節點總結之讀取xml文檔節點
2)在Java中使用xpath方法,主要有兩點:
List<Node> selectNodes("xpath運算式"); 查詢多個節點對象
Node selectSingleNode("xpath運算式"); 查詢一個節點對象
下面就用執行個體說明使用方法。

一、selectNodes使用方法:

 1 package com.vastsum.demo; 2  3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.util.List; 6  7 import org.dom4j.Document; 8 import org.dom4j.Element; 9 import org.dom4j.Node;10 import org.dom4j.io.OutputFormat;11 import org.dom4j.io.SAXReader;12 import org.dom4j.io.XMLWriter;13 14 /**15  * 16  * @author shutu00817  *selectNode的使用方法18  */19 public class xpathDemo {20 21     public static void main(String[] args) throws Exception {22 23     Document doc = new SAXReader().read(new File("./src/contact.xml"));24         25         /**26          * @param xpath 表示xpath文法變數27          */28     String xpath="";29         30         /**31          * 1.      /      絕對路徑      表示從xml的根位置開始或子項目(一個階層)32          */33         xpath = "/contactList";34         xpath = "/contactList/contact";35         36         /**37          * 2. //     相對路徑       表示不分任何階層的選擇元素。38          */39         xpath = "//contact/name";40         xpath = "//name";41         42         /**43          * 3. *      萬用字元         表示匹配所有元素44          */45         xpath = "/contactList/*"; //根標籤contactList下的所有子標籤46         xpath = "/contactList//*";//根標籤contactList下的所有標籤(不分階層)47         48         /**49          * 4. []      條件           表示選擇什麼條件下的元素50          */51         //帶有id屬性的contact標籤52         xpath = "//contact[@id]";53         //第二個的contact標籤54         xpath = "//contact[2]";55         //選擇最後一個contact標籤56         xpath = "//contact[last()]";57         58         /**59          * 5. @     屬性            表示選擇屬性節點60          */61         xpath = "//@id"; //選擇id屬性節點對象,返回的是Attribute對象62         xpath = "//contact[not(@id)]";//選擇不包含id屬性的contact標籤節點63         xpath = "//contact[@id='002']";//選擇id屬性值為002的contact標籤64         xpath = "//contact[@id='001' and @name='eric']";//選擇id屬性值為001,且name屬性為eric的contact標籤65         66         /**67          *6.  text()   表示選擇常值內容68          */69         //選擇name標籤下的常值內容,返回Text對象70         xpath = "//name/text()";71         xpath = "//contact/name[text()='張三']";//選擇姓名為張三的name標籤72         73         74         List<Node> list = doc.selectNodes(xpath);75         for (Node node : list) {76             System.out.println(node);77         }78     79         //寫出xml檔案80         //輸出位置81         FileOutputStream out = new FileOutputStream("d:/contact.xml");82         83         //指定格式84         OutputFormat format = OutputFormat.createPrettyPrint();85         format.setEncoding("utf-8");86         XMLWriter writer = new XMLWriter(out,format);87         88         //寫出內容89         writer.write(doc);90         91         //關閉資源92         writer.close();93         94     }95     96 97 }

二、selectSingleNode的使用方法

 1 package com.vastsum.demo; 2  3 import java.io.File; 4 import java.util.Iterator; 5  6 import org.dom4j.Attribute; 7 import org.dom4j.Document; 8 import org.dom4j.Element; 9 import org.dom4j.io.SAXReader;10 11 /**12  * 13  * @author shutu00814  *selectSingleNode的使用15  */16  public class xpathDemo1{17      public static void main(String[] args) throws Exception{18          //讀取XML檔案,獲得document對象19         SAXReader saxReader = new SAXReader();    20         Document doc = saxReader.read(new File("./src/contact.xml"));21         22         //使用xpath擷取某個節點23         String xpath = "";24         25         //對contact元素 id="001"的節點,操作26         xpath = "//contact[@id = '001']";27         Element contactElem =    (Element)doc.selectSingleNode(xpath);28         29         //設定這個節點的屬性值30         contactElem.addAttribute("name", "001");31         32         //輸出這個節點的所有屬性值33         for(Iterator it = contactElem.attributeIterator();it.hasNext();){34         Attribute conAttr = (Attribute)it.next();35         String conTxt = conAttr.getValue();36         String conAttrName = conAttr.getName();37         System.out.println(conAttrName+" = "+conTxt);38         }39         40      }41  }

 備忘:以下是操作的xml檔案

1 <?xml version="1.0" encoding="UTF-8"?> 2 <contactList id="0"> 3 <contact id="001" class="style" name="lisi"> 4 <name>張三</name> 5 <age>20</age> 6 <phone>134222223333</phone> 7 <email>zhangsan@qq.com</email> 8 <qq>432221111</qq> 9 </contact>10 <contact id="002">11 <name>李四</name>12 <age>20</age>13 <phone>134222225555</phone>14 <email>lisi@qq.com</email>15 <qq>432222222</qq>16 </contact>17 <contactTwo>18 <name>王五</name>19 <age>32</age>20 <phone>465431341</phone>21 <emali>af@qq.com</emali>22 <qq>46164694</qq>23 </contactTwo>24 <test>測試</test>25 <test>其他用途</test>26 </contactList>View Code

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.