How to Select an Attribute Based on Another Attribute Value Using XPath?

Select an attribute based on another attribute value on the same node using XPath

You can select an attribute depending on the value of another attribute on the same node, using the following xpath expression:

//root/node[@attributeToMatch="value"]/@attributeToSelect

This would only select @attributeToSelect if the node has an @attributeToMatch that equals to "value".

For example, let's suppose you have the following XML document:

<?xml version="1.0"?>
    <notes>
    <note id="note-1" lang="en">Call the office</note>
    <note id="note-2" lang="de">Freunde treffen</note>
    <note id="note-3" lang="en">Pickup groceries</note>
    <note id="note-4" lang="fr">Apprends le français</note>
</notes>

To select the id attribute only if lang attribute equals "en", you could use the following xpath expression:

//notes/note[@lang="en"]/@id

This would result in the following id attributes being selected:

id=note-1
id=note-3

Hope you found this post useful. It was published . Please show your love and support by sharing this post.