开发者

obtaining a unique set with javas xpath

开发者 https://www.devze.com 2023-01-02 17:45 出处:网络
Given the following xml document (assuming more books then actually listed) and using the java implementation of xpath.

Given the following xml document (assuming more books then actually listed) and using the java implementation of xpath. What expression would I use to find a unique set of author names?

<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">开发者_如何学Go
        <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>


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());
}

I used the excellent article "The Java XPath API" as a reference.

XPath Version 1.0 cannot, in general, select distinct values, so I inserted the authors into a Set. At the end of the for loop, the set will contain all of the authors.

0

精彩评论

暂无评论...
验证码 换一张
取 消