给出以下xml文档(假设实际列出了更多的书)并使用xpath的java实现.我将使用什么表达式来查找一组唯一的作者姓名?
<inventory>
<book year="2000">
<title>Snow Crash</title>
<author>Neal Stephenson</author>
<publisher>Spectra</publisher>
<isbn>0553380958</isbn>
<price>14.95</price>
</book>
<book year="2005">
<title>Burning Tower</title>
<author>Larry Niven</author>
<author>Jerry Pournelle</author>
<publisher>Pocket</publisher>
<isbn>0743416910</isbn>
<price>5.99</price>
</book>
<book year="1995">
<title>Zodiac</title>
<author>Neal Stephenson</author>
<publisher>Spectra</publisher>
<isbn>0553573862</isbn>
<price>7.50</price>
</book>
<!-- more books... -->
</inventory>
Run Code Online (Sandbox Code Playgroud)
Set<String> uniqueAuthors = new HashSet<String>();
XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath();
XPathExpression expr = xpath.compile("//book/author/text()");
NodeList nodes = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
uniqueAuthors.add(nodes.item(i).getNodeValue());
}
Run Code Online (Sandbox Code Playgroud)
我使用了优秀的文章" The Java XPath API "作为参考.
一般来说,XPath版本1.0不能选择不同的值,因此我将作者插入到Set.在for循环结束时,该集将包含所有作者.
| 归档时间: |
|
| 查看次数: |
872 次 |
| 最近记录: |