這篇文章給大家分享的是有關java如何使用xpath解析xml的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考。一起跟隨小編過來看看吧。
邯鄲ssl適用于網(wǎng)站、小程序/APP、API接口等需要進行數(shù)據(jù)傳輸應用場景,ssl證書未來市場廣闊!成為創(chuàng)新互聯(lián)的ssl證書銷售渠道,可以享受市場價格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18980820575(備注:SSL證書合作)期待與您的合作!
XPath即為XML路徑語言(XML Path Language),它是一種用來確定XML文檔中某部分位置的語言。XPath基于XML的樹狀結(jié)構(gòu),提供在數(shù)據(jù)結(jié)構(gòu)樹中找尋節(jié)點的能力。起初 XPath 的提出的初衷是將其作為一個通用的、介于XPointer與XSL間的語法模型。但是 XPath 很快的被開發(fā)者采用來當作小型查詢語言
XPathTest.java
package com.hongyuan.test; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class XPathTest { public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { // 解析文件,生成document對象 DocumentBuilder builder = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); Document document = builder.parse(new File("bookstore.xml")); // 生成XPath對象 XPath xpath = XPathFactory.newInstance().newXPath(); // 獲取節(jié)點值 String webTitle = (String) xpath.evaluate( "/bookstore/book[@category='WEB']/title/text()", document, XPathConstants.STRING); System.out.println(webTitle); System.out.println("==========================================================="); // 獲取節(jié)點屬性值 String webTitleLang = (String) xpath.evaluate( "/bookstore/book[@category='WEB']/title/@lang", document, XPathConstants.STRING); System.out.println(webTitleLang); System.out.println("==========================================================="); // 獲取節(jié)點對象 Node bookWeb = (Node) xpath.evaluate( "/bookstore/book[@category='WEB']", document, XPathConstants.NODE); System.out.println(bookWeb.getNodeName()); System.out.println("==========================================================="); // 獲取節(jié)點集合 NodeList books = (NodeList) xpath.evaluate("/bookstore/book", document, XPathConstants.NODESET); for (int i = 0; i < books.getLength(); i++) { Node book = books.item(i); System.out.println(xpath.evaluate("@category", book, XPathConstants.STRING)); } System.out.println("==========================================================="); } }
bookstore.xml
Everyday Italian Giada De Laurentiis 2005 30.00 Harry Potter J K. Rowling 2005 29.99 Learning XML Erik T. Ray 2003 39.95
感謝各位的閱讀!關于java如何使用xpath解析xml就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!