//通过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();
}
}
@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();
}
}