JavaEE XML XPath

來源:互聯網
上載者:User

標籤:for   amp   輸出   開始   位置   class   ack   多節點   tno   

JavaEE XML XPath

@author ixenos

 

 

XPath技術1 引入

問題:當使用dom4j查詢比較深的階層的節點(標籤,屬性,文本),比較麻煩!!!需要遍曆DOM樹的眾多節點來進行尋找!

比如rootEle.element(“dsfs”).element(“sdfsf”)element(“sdfsf”). element(“aim”)

 2 xPath作用

主要是用於快速擷取所需的節點對象。

(XSLT中的match屬性的值就使用XPath!!!)

 

3 在dom4j中如何使用xPath技術

1)匯入xPath支援jar包 。  jaxen-1.1-beta-6.jar

2)使用xpath方法

List<Node>  selectNodes("xpath運算式");   查詢多個節點對象

Node       selectSingleNode("xpath運算式");  查詢一個節點對象

 

4 xPath文法

/      絕對路徑      表示從xml的根位置開始或子項目(一個階層)

//     相對路徑       表示不分任何階層的選擇元素。

*      萬用字元         表示匹配所有元素

[]      條件           表示選擇什麼條件下的元素

@     屬性            表示選擇屬性節點

and     關係          表示條件的與關係(等價於&&)

text()    文本           表示選擇常值內容

 

樣本:

XPath可以描述XML文檔中的一個節點集

/grib/row 

描述了grib的子項目(每一個grib)中所有的row元素

 

/grib/row[1] 

用[]選擇特定元素,這表示第一行(索引從1開始)

 

/grib/row[1]/cell[1]/@anchor

用@得到屬性值,這描述了第一行第一個儲存格的anchor屬性

 

/grib/row/cell/@anchor

描述了作為根項目的grib的子項目的那些row元素中所有cell的anchor屬性

 

 

/** * 1.  /      絕對路徑      表示從xml的根位置開始或子項目(一個階層) */xpath = "/contactList";xpath = "/contactList/contact";/** * 2. //     相對路徑       表示不分任何階層的選擇元素。 */xpath = "//contact/name";xpath = "//name";/** * 3. *      萬用字元         表示匹配所有元素 */xpath = "/contactList/*"; //根標籤contactList下的所有子標籤xpath = "/contactList//*";//根標籤contactList下的所有標籤(不分階層)/** * 4. []      條件           表示選擇什麼條件下的元素 *///帶有id屬性的contact標籤xpath = "//contact[@id]";//第二個的contact標籤xpath = "//contact[2]";//選擇最後一個contact標籤xpath = "//contact[last()]";/** * 5. @     屬性            表示選擇屬性節點 */xpath = "//@id"; //選擇id屬性節點對象,返回的是Attribute對象xpath = "//contact[not(@id)]";//選擇不包含id屬性的contact標籤節點xpath = "//contact[@id=‘002‘]";//選擇id屬性值為002的contact標籤xpath = "//contact[@id=‘001‘ and @name=‘eric‘]";//選擇id屬性值為001,且name屬性為eric的contact標籤/** *6.  text()   表示選擇常值內容 *///選擇name標籤下的常值內容,返回Text對象xpath = "//name/text()";xpath = "//contact/name[text()=‘張三‘]";//選擇姓名為張三的name標籤

  更多XPath運算式請看XPath Tutorial

 

Demo:
import java.io.File;import java.io.FileOutputStream;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;/** * 第一個xpath程式 * @author ixenos * */public class Demo1 {public static void main(String[] args) throws Exception{/** * 需求: 刪除id值為2的學生標籤 */Document doc = new SAXReader().read(new File("e:/student.xml"));//1.查詢id為2的學生標籤//使用xpath技術Element stuElem = (Element)doc.selectSingleNode("//Student[@id=‘2‘]");//2.刪除標籤stuElem.detach();//3.寫出xml檔案FileOutputStream out = new FileOutputStream("e:/student.xml");OutputFormat format = OutputFormat.createPrettyPrint();format.setEncoding("utf-8");XMLWriter writer = new XMLWriter(out,format);writer.write(doc);writer.close();}}

  

 

 

簡要樣本

 1) 用XPath定位標籤,進行修改操作

package com.ixenos.xpath;import java.util.List;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.SAXReader;import com.ixenos.dom4j.CreateXML;/** * 在TestXPath的基礎上改進了: * 將精準定位全交給XPath去做,因此刪除了modEle多餘的屬性定位判斷 *  * @author ixenos * */public class TestXPath2 {/** * 讀取XML檔案產生Docment *  * @throws Exception */public static Document getDoc(String path) throws Exception {Document doc = new SAXReader().read(path);return doc;}/** * XPath定位標籤 */@SuppressWarnings("unchecked")public static List<Element> getEle(Document doc, String xpath) {return (List<Element>)doc.selectNodes(xpath);}/** * 對指定標籤的屬性進行修改 *  * @param func *            修改功能選擇 * @param eleList *            被修改的標籤list * @param locateAttr *            用於定位標籤的屬性 * @param locateAttrValue *            用於定位標籤的屬性的屬性值 * @param aimChild *            想要修改的子標籤 * @param aimChildText *            想要修改的新的子標籤文本值 */public static void modEle(String func, List<Element> eleList, String aimChild, String aimChildText) {// 取出for (Element ele : eleList) {// 修改功能選擇if ("delete".equals(func)) {ele.detach();} else if ("modify".equals(func)) {// 修改指定屬性的屬性值// element(name)指定第一個標籤名為name的標籤// setText修改Text,addText追加Textele.element(aimChild).setText(aimChildText);}}}/** * 將DOM樹輸出為XML檔案 *  * @throws Exception */public static void writeXML(Document doc, Boolean pretty, String encoding) throws Exception {CreateXML.writeXML(doc, pretty, encoding);}/** * 測試 *  * @param args * @throws Exception */public static void main(String[] args) throws Exception {Document doc = getDoc("demo.xml");//得到所有id屬性值為2的Student標籤List<Element> eleList = getEle(doc, "//Student[@id=‘2‘]");modEle("modify", eleList, "name", "李爾雅");// modEle("delete", eleList, null, null);writeXML(doc, true, "utf-8");}}

  

修改結果:

<?xml version="1.0" encoding="utf-8"?><Students>   <Student id="1">     <name>張三</name>      <gender>男</gender>      <grade>物聯網一般</grade>      <address>廣州白雲</address>   </Student>    <Student id="2">     <name>爾雅</name>      <gender>女</gender>      <grade>物聯網二班</grade>      <address>廣州海珠</address>   </Student> </Students>

  

 2) 用XPath讀取一個規範的html檔案(比如xhtml)

import java.io.File;import java.util.Iterator;import java.util.List;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.SAXReader;/** * 使用xpath技術讀取一個規範的html文檔 * @author ixenos * */public class Demo4 {public static void main(String[] args) throws Exception{Document doc = new SAXReader().read(new File("./src/personList.html"));//System.out.println(doc);//讀取title標籤Element titleElem = (Element)doc.selectSingleNode("//title");String title = titleElem.getText();System.out.println(title);/** * 練習:讀取連絡人的所有資訊 * 按照以下格式輸出: *  編號:001 姓名:張三 性別:男 年齡:18 地址:xxxx 電話: xxxx *       編號:002 姓名:李四 性別:女 年齡:20 地址:xxxx 電話: xxxx *       ...... *///1.讀取出所有tbody中的tr標籤List<Element> list = (List<Element>)doc.selectNodes("//tbody/tr");//2.遍曆for (Element elem : list) {//編號//String id = ((Element)elem.elements().get(0)).getText();String id = elem.selectSingleNode("td[1]").getText();//姓名String name = ((Element)elem.elements().get(1)).getText();//性別String gender = ((Element)elem.elements().get(2)).getText();//年齡String age = ((Element)elem.elements().get(3)).getText();//地址String address = ((Element)elem.elements().get(4)).getText();//電話String phone = ((Element)elem.elements().get(5)).getText();System.out.println("編號:"+id+"\t姓名:"+name+"\t性別:"+gender+"\t年齡:"+age+"\t地址:"+address+"\t電話:"+phone);}}}

  

JavaEE XML XPath

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.