XPath for attribute value

After struggling with attributes for a long time, I finally discovered the easy way to obtain the text value of an attribute in a XML file with a XPath expression. Let’s say you got the following XML-file

<messages>
  <note id="501">
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
  </note>
  <note id="502">
    <to>Jani</to>
    <from>Tove</from>
    <heading>Re: Reminder</heading>
    <body>I will not</body>
  </note>
</messages>

To get the value of the id attribute of the first note use an Xpath-expression with a string function

[ string( //note[1]/@id ) ]
and you get 501.

About the author

haiko By Haiko van der Schaaf Google