XML編程總結(七)——使用XPath物件查詢xml文檔,xpathxml

來源:互聯網
上載者:User

XML編程總結(七)——使用XPath物件查詢xml文檔,xpathxml

(七)使用XPath物件查詢xml文檔

 XPath,一種為查詢 XML 文檔而設計的查詢語言。XPath 並不是 Java 語言,事實上 XPath 不是一種完整的程式設計語言。有很多東西用 XPath 表達不出來,甚至有些查詢也無法表達。幸運的是,可以把 XPath 結合到 Java 程式中,這樣就能發揮兩者的優勢了:Java 做 Java 所擅長的,XPath 做 XPath 所擅長的。Java 程式執行 XPath 查詢所需要的API(API)還因形形色色的 XPath 引擎而各不相同。Xalan 有一種 API,Saxon 使用另一種,其他引擎則使用其他的 API。Java 5 推出了 javax.xml.xpath 包,提供一個引擎和物件模型獨立的 XPath 庫。

在 Java 中計算 XPath 運算式時,第二個參數指定需要的傳回型別。有五種可能,都在javax.xml.xpath.XPathConstants 類中命名了常量:

  • XPathConstants.NODESET
  • XPathConstants.BOOLEAN
  • XPathConstants.NUMBER
  • XPathConstants.STRING
  • XPathConstants.NODE

測試代碼:

 1 public class XPathTest { 2     /** 3      * 使用不帶命名空間的XPath查詢 4      * @throws Exception 5      */ 6     @Test 7     public void testRetrieveOndNode() throws Exception{ 8         //獲得xml文檔的記憶體模型 9         DocumentBuilder builder = DocumentBuilderFactory10         .newInstance().newDocumentBuilder();11         Document document = builder.parse(new File("src/main/resource/books.xml"));12         //建立XPathFactory對象13         XPathFactory xPathFactory = XPathFactory.newInstance();14         //獲得XPath對象15         XPath xPath = xPathFactory.newXPath();16         //建立XPath運算式對象17         XPathExpression nodeExpr = xPath.compile("//book[1]");18         //執行XPath運算式,因為該運算式只能獲得一個節點,所以用XPathConstants.NODE19         Element element = (Element) nodeExpr.evaluate(document, XPathConstants.NODE);20         NodeList nodes = element.getChildNodes();21         for(int i=0;i<nodes.getLength();i++){22             Node node = nodes.item(i);23             //獲得節點類型24             short nodeType = node.getNodeType();25             if(nodeType==Node.ELEMENT_NODE){26                 //獲得節點文本,getNodeValue()無法獲得節點的文本27                 String text=node.getTextContent();28                 System.out.println(node.getNodeName()+"--"+text);29             }30         }31     }32 }

 

聯繫我們

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