Selecting Things Besides Elements with Location Paths

Up until now, we’ve discussed XPath expressions that used either element names (/sonnet/lines/line) or special characters (/ or ..) to select elements from an XML document. Obviously, XML documents contain things other than elements; we’ll talk about how to select those other things here.

Selecting attributes

To select an attribute, use the at-sign (@) along with the attribute name. In our sample sonnet, you can select the type attribute of the <sonnet> element with the XPath expression /sonnet/@type. If the context node is the <sonnet> element itself, then the relative XPath expression @type does the same thing.

Selecting the text of an element

To select the text of an element, simply refer to it in your expression. The element <xsl:value-of select="/sonnet/auth:author/last-name"/> returns Shakespeare for our sample sonnet. You can also use the string() function, although that’s typically not necessary.

These XSLT instructions:

<xsl:value-of select="/sonnet/something_else:author/first-name"/>
<xsl:text> </xsl:text>
<xsl:value-of select="/sonnet/something_else:author/last-name/string()"/>

generate these results:

William Shakespeare

Be aware that getting the text of an element with children probably doesn’t do what you want. For example, the element <xsl:value-of select="/sonnet/auth:author"/> returns the string ShakespeareWilliamBritish15641616. All of the text descendants of the <auth:author> node are concatenated together. To format ...

Get XSLT, 2nd Edition 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.