Search code examples
javaxmlxpathnodelist

Return string values of NodeList from a parsed XML doc


Given the xml snippet:

<AddedExtras>
    <AddedExtra Code="1234|ABCD" Quantity="1" Supplier="BDA"/>
    <AddedExtra Code="5678|EFGH" Quantity="1" Supplier="BDA"/>
    <AddedExtra Code="9111|ZXYW" Quantity="1" Supplier="BDA"/>
    <AddedExtra Code="9188|ZXYF" Quantity="1" Supplier="BDA"/>
    <AddedExtra Code="9199|ZXYG" Quantity="1" Supplier="BDA"/>
</AddedExtras>

And the following snippet which reads in the above xml as a parsed doc and uses an xpath expression to extract the 'Code' attribute:

public String getNodeValuesFromNodeList(Document doc, String expression){

NodeList nodeList = null;
    try {
        nodeList = (NodeList) xpath.compile(expression).evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    return nodeList.toString();
}

The returned list is an Object (org.apache.xml.dtm.ref.DTMNodeList@58cf8f94) and not a list of Strings - how can I return the nodeList such that it returns the following as a list of Strings:

    Code="1234|ABCD
    Code="5678|EFGH
    Code="9111|ZXYW
    Code="9188|ZXYF
    Code="9199|ZXYG

Then, how can I return only the first 2 (as an example)?


Solution

  • If your XPath expression selects attributes, and you want the values of the attributes, then you can use a loop similar to the following:

        List<String> codes = new ArrayList<>();
        for (int i = 0; i < nodeList.getLength(); ++i) {
            Attr attr = (Attr)nodeList.item(i);
            codes.add(attr.getValue());
        }