alex_and_ra
alex_and_ra

Reputation: 219

Get sibling of an XML node with XPath

I have the following XML

    <field label="mapping">
       <tuple> <atom label="A"/> <atom label="X"/> </tuple>
       <tuple> <atom label="B"/> <atom label="Y"/> </tuple>
       <tuple> <atom label="C"/> <atom label="Z"/> </tuple>
    </field>

I want to select the label of the second atom node from a tuple when I know the label of the other atom.

For example, if I know the atom with the label A, I want to get the atom with the label X.

I wrote this XPath expression, but it doesn't do the trick:

//following-sibling::field[@label = 'mapping']/tuple/atom[@label = 'A']

If I write

XPath expr = xpath.compile("//following-sibling::field[@label = 'mapping']/tuple/atom[@label = 'A']");
NodeList nodes = ((NodeList) expr.evaluate(doc, XPathConstants.NODESET));
for (int j=0;j<nodes.getLength();j++){
    String label = nodes.item(j).getAttributes().getNamedItem("label").getNodeValue();
}

the variable label is A, when I expect it to be X.

What am I doing wrong?

Upvotes: 1

Views: 2006

Answers (1)

JWiley
JWiley

Reputation: 3209

You have the following-sibling axis in the wrong place, but that's close:

//field[@label = 'mapping']/tuple/atom[@label = 'A']/following-sibling::atom

Upvotes: 1

Related Questions