锁定老帖子 主题:编写简单的XPath程序
精华帖 (1) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2008-01-05
当前使用XPath 1.0
<inventory> <book year="2000"> <title>Thinking in Java</title> <author>TEST</author> <publisher>JQGYCBS</publisher> <isbn>80958</isbn> <price>98.95</price> </book> <book year="2005"> <title>ROR</title> <author>TEST</author> <publisher>DZGYCBS</publisher> <isbn>0743416910</isbn> <price>65.99</price> </book> <book year="1995"> <title>H</title> <author>King</author> <publisher>Sc</publisher> <isbn>0553862</isbn> <price>77.50</price> </book> </inventory>
//book[author="TEST"] book代表节点的名称,author属性的名称,后面是要查询的值
//book[author="TEST"]/title title代表要取元素的名称
//book[author="TEST"]/title/text() text()该节点的内容
//用 JAXP 解析文档 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // never forget this! factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse("src/books.xml");
XPathFactory pathFactory = XPathFactory.newInstance();
XPath xpath = pathFactory.newXPath();
XPathExpression pathExpression = xpath.compile("//book[author='TEST']/title/text()");
Object result = pathExpression.evaluate(doc, XPathConstants.NODESET); //doc是Document对象名,XPathConstants代表XPath常量,NODESET是XPath 1.0 NodeSet数据类型 //XPathConstants.NODESET将XPathConstants常量返回NODESET类型
NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i).getNodeValue()); }
package book; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; public class Test { public static void main(String[] args) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // never forget this! DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse("src/books.xml"); XPathFactory pathFactory = XPathFactory.newInstance(); XPath xpath = pathFactory.newXPath(); XPathExpression pathExpression = xpath .compile("//book[author='TEST']/title/text()"); Object result = pathExpression.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i).getNodeValue()); } } }
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2008-01-05
详细看下先
|
|
返回顶楼 | |
发表时间:2008-01-29
貌似抄袭IBM development网站的内容:
http://www.ibm.com/developerworks/cn/xml/x-javaxpathapi.html |
|
返回顶楼 | |
发表时间:2008-01-31
本人承认,该技术来源于IBM Development,该blog是我的技术总结.谢谢支持!
|
|
返回顶楼 | |
浏览 9022 次