Selecting an attribute with XPath can be done using attribute:: or @.

Example of accessing attributes with XPath

<?xml version="1.0" encoding="UTF-8"?>

<data>

    <employee>       

        <office>

            <dept id="accounts">

            <name>Raju</name>

            <age>50<age>

            </dept>

        </office>

        <office>

            <dept id="HR">

            <name>Malini</name>

            <age>30<age>

            </dept>

        </office>        

    </employee>

</data>

Accessing attributes with XPath

Expression

Description

Example (from document given above)

@

Select attributes. It is abbreviation of attribute::

/dept/@id  or child::dept/attribute::id – Selects id attribute on dept element.

dept[@id]  – All <dept> elements with “id” attribute.

//@id – Selects all attributes that are named “id”.

Predicates

Predicates for attributes are given in table below:

Predicate for attribute nodes

Path Expression

Result

//office[@id]

Selects all office elements that have an attribute ‘id’.

//office[@id=’HR’]

Selects all office elements that have an attribute ‘id’ with value “HR”.

Wildcards

XPath wildcards are used to select XML attributes regardless of their name.

Wildcards in attribute nodes

Wildcard

Description

Example

@*

Selects all attributes of current node

//data[@*]  - Selects all elements from data node which has atleast one attribute.

 

›› go to examples ››