使用stax操作xml(6)

//通過xpath獲取方式
@Test
public void test06() throws IOException, ParserConfigurationException, SAXException, XPathExpressionException{
InputStream is=TestStax.class.getClassLoader().getResourceAsStream("books.xml");
//創建文檔處理對象
DocumentBuilder db=DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc=db.parse(is);
//創建xpath對象
XPath xPath=XPathFactory.newInstance().newXPath();
//第一個參數表達式,第二個文檔,第三個參數是返回類型
NodeList list=(NodeList) xPath.evaluate("//book[@category='WEB']", doc,XPathConstants.NODESET);
for (int i = 0; i < list.getLength(); i++) {
Element e=(Element) list.item(i);
System.out.println(e.getElementsByTagName("title").item(0).getTextContent());
}

if(is!=null){
is.close();
}
}
發佈了46 篇原創文章 · 獲贊 3 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章