用DOM解析XML ,用xpath快速查詢XML節點
阿新 • • 發佈:2018-11-11
XPath是一種快速查詢xml節點和屬性的一種語言,Xpath和xml的關係就像是sql語句和資料庫的關係。用sql語句可以從資料庫中快速查詢出東西同樣的用xPath也可以快速的從xml中查詢出東西。
下面的示例演示了怎麼用jdk自帶的rt.jar完成dom解析
程式碼如下:
test.xml的程式碼如下:
<?xml version="1.0" encoding="UTF-8" ?> <inventory> <book year="2012"> <title>菜根譚</title> <author>洪應明</author> <dynasty>明朝</dynasty> <price>38</price> </book> <book year="2013"> <title>曾國藩家書</title> <author>曾國藩</author> <dynasty>清朝</dynasty> <price>89</price> </book> <book year="2014"> <title>高等代數</title> <author>丘維聲</author> <dynasty>中華人民共和國</dynasty> <price>86</price> </book> </inventory>
ParseXmlTest的程式碼如下:
package com.timo.xml; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.*; import java.io.File; /** * @author Abraham Qin * @since 2018/11/11 */ public class ParseXmlTest {
//查詢價格大於40的書的標題的內容 private static final String XPath_EXPRESSION = "//book[price>40]/title/text()"; public static void main(String[] args) throws Exception { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); //開啟驗證: documentBuilderFactory.setValidating(true); documentBuilderFactory.setNamespaceAware(false); documentBuilderFactory.setIgnoringComments(true); documentBuilderFactory.setIgnoringElementContentWhitespace(true); documentBuilderFactory.setCoalescing(false); documentBuilderFactory.setExpandEntityReferences(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); //設定異常處理: documentBuilder.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { System.out.println("warn:" + exception.getMessage()); } @Override public void error(SAXParseException exception) throws SAXException { System.out.println("error:" + exception.getMessage()); } @Override public void fatalError(SAXParseException exception) throws SAXException { System.out.println("fatalError:" + exception.getMessage()); } }); //將test.xml載入到一個Document的物件中: String filePath = "E:\\mybatis-indepth-research\\mybatis-3\\src\\main\\java\\com\\timo\\xml\\test.xml"; Document document = documentBuilder.parse(new File(filePath)); //查詢author為洪應明的title: processParseXmlWithXpath(document,XPath_EXPRESSION ); } private static void processParseXmlWithXpath(Document document, String xPathExpression) throws Exception { //建立XPathFactory: XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); XPathExpression expression = xPath.compile(xPathExpression); Object result = expression.evaluate(document, XPathConstants.NODESET); if (result instanceof NodeList) { NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { System.out.println(String.format("%s=%s", nodes.item(i).getNodeName(), nodes.item(i).getNodeValue())); } } } }