Search code examples
javaxmlxpathattributesnodelist

Get attributes from nodelist using xpath in Java


XML

    <Employees>
<Employee id="1" name="xyz">
<Employee id="2" name="abc">
</Employees>

I can get the list of Employee node with xpath expression

XPathExpression expr=xpath.compile("/Employees/Employee");
            NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

How to get the attributes id, name from each node in the list.


Solution

  • You cannot ask a single list returning 2-tuples of (id, name) But you can have this in two separate node lists:

    XPathExpression expr1 = xpath.compile("/Employees/Employee/@id");
    NodeList nodes1 = (NodeList) expr1.evaluate(doc, XPathConstants.NODESET);
    
    XPathExpression expr2 = xpath.compile("/Employees/Employee/@name");
    NodeList nodes2 = (NodeList) expr2.evaluate(doc, XPathConstants.NODESET);
    

    However, if having a single list is such important, some workaround are possible, for instance by concatenating both attributes values into a csv-like string:

    XPathExpression expr = xpath.compile("concat(/Employees/Employee/@id, ';', /Employees/Employee/@name)");
    

    which will return a list of 2 nodes:

    "1;xyz"
    "2;abc"