如果要定位某個XML文檔中的一段特性信息,那么通過遍歷DOM樹的眾多節(jié)點來進行查找顯得有些麻煩。XPath是的訪問樹節(jié)點變得很容易熬北。
需要先了解Java XML解析嚎京,可以參考Java驗證解析XML
場景
<bookstore>
<book id="book1">
<name>Java 核心技術(shù)</name>
<author>Cornell </author>
<year>2014</year>
<price>89</price>
</book>
<book id="book2">
<name>深入淺出MyBatis</name>
<author>楊開振</author>
<year>2016</year>
<price>69</price>
</book>
<book id="book3">
<name>Java RESTful Web Service實戰(zhàn)</name>
<author>韓陸</author>
<year>2016</year>
<price>59</price>
</book>
</bookstore>
如果需要得到author節(jié)點,可以通過XPath表達式/bookstore/book/author來得到所有的author節(jié)點业舍。java代碼如下玖详。
/**
* @author gethin
* @version 創(chuàng)建時間:2018年4月8日 下午3:17:04
* 類說明
*/
public class ReadXMLByDOMWithXpath {
private static DocumentBuilderFactory dBuilderFactory = null;
private static DocumentBuilder dBuilder = null;
private static XPathFactory xPathFactory = null;
private static XPath xPath = null;
static {
try {
/**
* 要讀入一個XML文檔,首先要有一個DocumentBuilder對象 可以從DocumentBuilderFactory中得到這個對象
*/
dBuilderFactory = DocumentBuilderFactory.newInstance();
//設(shè)置驗證
dBuilderFactory.setValidating(true);
//忽略空白字符節(jié)點
dBuilderFactory.setIgnoringElementContentWhitespace(true);
dBuilder = dBuilderFactory.newDocumentBuilder();
xPathFactory = XPathFactory.newInstance();
xPath = xPathFactory.newXPath();
dBuilder.setErrorHandler(new ErrorHandler() {
public void warning(SAXParseException exception) throws SAXException {
throw exception;
}
public void fatalError(SAXParseException exception) throws SAXException {
// TODO Auto-generated method stub
throw exception;
}
public void error(SAXParseException exception) throws SAXException {
// TODO Auto-generated method stub
throw exception;
}
});
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//獲得所有的author節(jié)點并輸出
public static void showAuthorByXPath(String fileName) throws SAXException, IOException, XPathExpressionException {
Document document = dBuilder.parse(fileName);
NodeList nodeList = (NodeList) xPath.evaluate("/bookstore/book/author", document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Element author = (Element) nodeList.item(i);
System.out.println(author.getTextContent().trim());
}
}
public static List<Book> listBooksWithXpath(String fileName)
throws XPathExpressionException, SAXException, IOException {
List<Book> books = new ArrayList<Book>();
// 可通過DocumentBuilder對象的parse()方法讀入整個文檔
Document document = dBuilder.parse(fileName);
// 獲得所有book節(jié)點
NodeList nodeList = (NodeList) xPath.evaluate("/bookstore/book", document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Element bookElement = (Element) nodeList.item(i);
// 獲得該book節(jié)點下的所有屬性節(jié)點
NodeList bookAttribute = bookElement.getChildNodes();
// 用來存儲第i個節(jié)點的內(nèi)容
List<String> bookContent = new ArrayList<String>();
Book book = new Book();
book.setId(Integer.parseInt(bookElement.getAttribute("id").replace("book", "").trim()));
for (int j = 0; j < bookAttribute.getLength(); j++) {
Element atturbute = (Element) bookAttribute.item(j);
bookContent.add(atturbute.getTextContent().trim());
}
book.setName(bookContent.get(0));
book.setAuthor(bookContent.get(1));
book.setYear(Integer.parseInt(bookContent.get(2)));
book.setPrice(Integer.parseInt(bookContent.get(3)));
books.add(book);
}
return books;
}
public static void main(String args[]) {
String fileName = "./src/main/java/com/gethin/xmlparser/bookstore.xml";
try {
List<Book> books = ReadXMLByDOMWithXpath.listBooksWithXpath(fileName);
for (Book book : books) {
System.out.println(book);
}
showAuthorByXPath(fileName);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
運行截圖:
請參考勤讽,源碼github鏈接