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

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


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"?>
    <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>

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


This would result in the following id attributes being selected:


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.