Accessing Attributes

Selecting attributes is another important use of XPath. You learned earlier that you can use the @ character as an abbreviation for attribute::. You can use the following short XML document to illustrate how to select attributes.

<book edition="1st" language="English"> 
<introduction>Some introduction text</introduction> 
<chapter number="1"> 
Some Chapter 1 text. 
</chapter> 
<chapter number="2"> 
Some Chapter 2 text. 
</chapter> 
<chapter > 
Some Chapter 3 text. 
</chapter> 
<appendix designation="A"> 
Appendix A's content 
</appendix> 
</book> 

If you want to select the edition attribute on the book element, you can write this:

/book/@edition 

It might help you understand this to look at the unabbreviated form:

 /child::book/attribute::edition ...

Get Sams Teach Yourself XML in 10 Minutes now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.