After The End

Java的xpath示例程序

代码示例来源于:http://www.ibm.com/developerworks/xml/library/x-javaxpathapi.html
books.xml
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <inventory>
 3     <book year="2000">
 4         <title>Snow Crash</title>
 5         <author>Neal Stephenson</author>
 6         <publisher>Spectra</publisher>
 7         <isbn>0553380958</isbn>
 8         <price>14.95</price>
 9     </book>
10  
11     <book year="2005">
12         <title>Burning Tower</title>
13         <author>Larry Niven</author>
14         <author>Jerry Pournelle</author>
15         <publisher>Pocket</publisher>
16         <isbn>0743416910</isbn>
17         <price>5.99</price>
18     </book>
19  
20     <book year="1995">
21         <title>Zodiac</title>
22         <author>Neal Stephenson</author>
23         <publisher>Spectra</publisher>
24         <isbn>0553573862</isbn>
25         <price>7.50</price>
26     </book>
27 
28     <!-- more books -->
29  
30 </inventory>

 1 package com.zhanjh.xpath;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.xml.parsers.*;
 6 import javax.xml.xpath.*;
 7 
 8 import org.w3c.dom.*;
 9 import org.xml.sax.SAXException;
10 
11 class XpathSample {
12     public static void main(String[] args) throws ParserConfigurationException,
13             SAXException, IOException, XPathExpressionException {
14         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
15         factory.setNamespaceAware(true);
16         DocumentBuilder builder = factory.newDocumentBuilder();
17         Document doc = builder.parse("XmlFile/books.xml");
18         XPathFactory xFactory = XPathFactory.newInstance();
19         XPath xpath = xFactory.newXPath();
20         XPathExpression expr = xpath
21                 .compile("//book[author='Neal Stephenson']/price/text()");
22         Object result = expr.evaluate(doc, XPathConstants.NODESET);
23         NodeList nodes = (NodeList) result;
24         for (int i = 0; i < nodes.getLength(); i++) {
25             System.out.println(nodes.item(i).getNodeValue());
26         }
27     }
28 
29 }
30 
文件结构:
    XpahtSample/
       src/
          com.zhanjh.xpath
    XmlFile/
       books.xml


posted on 2007-12-11 16:06  zhanjh  阅读(2875)  评论(1)    收藏  举报

导航