What can I do to select an attribute value using XPATH query?

81 views Asked by At

I am pretty new in XPATH and I have the following problem:

I have this XML content:

<root><status>
  <id>0</id>
  <message>MY MESSAGE</message>
</status>
<drivers>
<drive id="my ID">
  <property1>0</property1>
  <property2>104857600</property2>
  <property3 />
</drive></drivers>
</root>

What have I to do to select the attribute value named id (I wanto select the "my ID value)

Can you help me?

Tnx

Andrea

2

There are 2 answers

0
Mike Sokolov On

To get the attribute node, you can do:

/root/drivers/drive/@id

or

/root/drivers/drive/attribute::id

In most cases this will automatically be converted to a string ('atomized') for you, but in a case where you need to ensure that you are getting back a string value, you can also do:

/root/drivers/drive/@id/string()
0
Kloe2378231 On

This should work:

/root/drivers/drive[1]/@id/text()

equivalent to:

//drive[1]/@id/text()

See there for more XPATH syntax explanation: http://www.w3schools.com/xpath/xpath_intro.asp