How to Select Attributes Using XPath?

Find out how you can get a node's attribute value with XPath

In xpath, the @ prefix denotes an attribute. To select all attributes, you would use a xpath expression like the following:

//root/node/@attribute

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 "lang" attributes, you can use the following xpath expression:

//notes/note/@lang

This will result in the following:

lang=en
lang=de
lang=en
lang=fr

To only select the attribute from the second note, for example, you can use the following xpath expression:

//notes/note[2]/@lang

This will result in the following attribute being selected:

lang=de

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