About Me

Friday, 13 April 2012

XPath - Attribute

XPath - Attribute

You have already learned how to select any element in an XML document, but how would you get that element's attribute? Those attributes values are within your reach once you learn how to use @ !


We will be using our lemonade2.xml file, which you can download.

XML Code, lemonade2.xml:

<inventory>
 <drink>
  <lemonade supplier="mother" id="1">
   <price>$2.50</price>
   <amount>20</amount>
  </lemonade>
  <pop supplier="store" id="2">
   <price>$1.50</price>
   <amount>10</amount>
  </pop>
 </drink>

 <snack>
  <chips supplier="store" id="3">
   <price>$4.50</price>
   <amount>60</amount>
   <calories>180</calories>
  </chips>
 </snack>

</inventory>

XPath - @ is for Attribute!

After you have figured out how to select an element in your XML document, just take it one step further to get the attribute.
At the end of your XPath expression, which is normally the element you want to select, add the at sign "@" plus the name of the attribute you wish to select. The following XPath expression selects chips element.

XPath Expression:

inventory/snack/chips
If we wanted to select the supplier attribute of chips, we would add "@supplier" to our expression.

XPath Expression:

inventory/snack/chips@supplier
If we wanted to select the supplier attribute of pop, the XPath expression would have to be changed slightly.

XPath Expression:

inventory/drink/pop@supplier

0 comments:

Post a Comment