清单 4. 用固定的 XPath 表达式查询 XML 文档的完整程序
- importjava.io.IOException;
- importorg.w3c.dom.*;
- importorg.xml.sax.SAXException;
- importjavax.xml.parsers.*;
- importjavax.xml.xpath.*;
- publicclassXPathExample{
- publicstaticvoidmain(String[]args)
- throwsParserConfigurationException,SAXException,
- IOException,XPathExpressionException{
- DocumentBuilderFactorydomFactory=DocumentBuilderFactory.newInstance();
- domFactory.setNamespaceAware(true);//neverforgetthis!
- DocumentBuilderbuilder=domFactory.newDocumentBuilder();
- Documentdoc=builder.parse("books.xml");
- XPathFactoryfactory=XPathFactory.newInstance();
- XPathxpath=factory.newXPath();
- XPathExpressionexpr
- =xpath.compile("//book[author='NealStephenson']/title/text()");
- Objectresult=expr.evaluate(doc,XPathConstants.NODESET);
- NodeListnodes=(NodeList)result;
- for(inti=0;i<nodes.getLength();i++){
- System.out.println(nodes.item(i).getNodeValue());
- }
- }
- }