How to Select an XML Node by Attribute Value Using XPath?

In xpath, the @ prefix denotes an attribute. To select all nodes that have a particular attribute value, you can use the following xpath expression:

//root/node[@attribute="value"]

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

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

To select all nodes that have the attribute lang="en", you could use the following xpath expression:

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

This would select the following two nodes:

<note lang="en">Call the office</note>
<note lang="en">Pickup groceries</note>

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.