Reputation: 385
I am trying traverse through an XML with XPath. I want to visit /group/isRequired[text()='Optional'] and travel one level up to grab the /bool node
I tried a few things like the below but can't seem to get it rit... appreciate any inputs.
I basically want to verify the Library node, group+isRequired node and the bool nodes in one statement.
//root/sample[library[text()='2']]/group/isRequired[text()='Optional']//bool[text()='true']
//root/sample[library[text()='2']]/group/isRequired[text()='Optional']../bool[text()='true']
//root/sample[library[text()='2']]/group/isRequired[text()='Optional']/bool[text()='true']
//root/sample[library[text()='2']]/group/isRequired[text()='Optional']/../bool[text()='true']
<root>
<sample>
<id>1</id>
<library>2</library>
<ruleName>Default</ruleName>
<group>
<groupID>1</groupID>
<groupName>orange</groupName>
<isRequired>Optional</isRequired>
</group>
<variant>1</variant>
<bool>true</bool>
</sample>
</root>
Upvotes: 0
Views: 1608
Reputation: 89305
You can go a different route, by filtering sample
node by group/isRequired
child, then you can continue from that sample
node to get to the bool
node :
//root/sample[library='2' and group/isRequired='Optional']/bool[.='true']
Upvotes: 1
Reputation: 93181
Simpler:
/root/sample[library = "2" and group/isRequired = "Optional" and bool = "true"]
You don't have to use /text()
to get the value of every node in the XPath. Depending on whether you XML has a schema, you don't need to put the literal values in quotes. Without it, everything is a string value, so I put them in quotes just for safety.
Upvotes: 1
Reputation: 28618
You need to move two steps up:
/root/sample[library[text()='2']]/group/isRequired[text()='Optional']/../../bool[text()='true']
But is much cleaner to put multiple conditions in one predicate:
/root/sample[library[text()='2'] and group/isRequired[text()='Optional'] and bool[text()='true']]
Upvotes: 1