Saturday, 16 July 2011

Example of Selecting an Attribute

XPath Attributes

To select an attribute using XPath, you prefix the attribute's name with a @ symbol.

Example of Selecting an Attribute

Consider the following XML document. Note that the "artist" node now has an attribute called "status":

 <albums>   <rock>     <title>Machine Head</title>     <artist status="active">Deep Purple</artist>   </rock>   <blues>     <title>Greens From The Garden</title>     <artist status="active">Cory Harris</artist>   </blues>   <country>     <title>The Ranch</title>     <artist status="disbanded">The Ranch</artist>   </country> </albums> 

If we wanted to select the "status" attribute of the "artist" node under the "rock" node, we could use the following expression:

 albums/rock/artist/@status 
Another Example

Attributes, just like any other node, can be the subject of a conditional statement. For example, imagine we're using XSLT to transform our XML document, and we want to select all "artist" nodes where the "status" attribute is set to "active". We could use the XSL "if" element to test the value.

Here's what we would write:

 <xsl:if test="@status = 'active'">  (content goes here) </xsl:if> 

No comments:

Post a Comment