120 likes | 256 Views
This document delves into the use of predicates in XPath to refine node selection. It explains how to filter nodes based on specific criteria, such as attribute values and positions, while highlighting the syntax for various scenarios. Examples include selecting elements with particular attribute values, excluding nodes with certain attributes, and using positional functions like `position()` and `last()`. Additionally, it emphasizes the importance of escaping certain characters in XML to avoid syntax conflicts and provides practical exercises for better understanding.
E N D
Predicates Elena Pierazzo 2006-2007
Intro • Part of XPath • Refine the filtering of selected nodes • Only nodes that correspond to the predicates assumption will be considered • Syntax: [predicate_content]
E.g. • Only elements that have a particular attribute value • Only elements that have a given position
Select nodes with given attribute values <xsl:template match="p[@audience='Instructor']"> <p><font color="red"><xsl:apply-templates/></font></p> </xsl:template>
Other examples with attributes • p[@audience != 'Instructor'] NOT EQUAL • p[@justify] • the value of the attribute doesn’t matter
And others • p[@WIDTH < 40] < 40 (i.e. 2, 35) • p[@WIDTH > 40] > 40 (i.e. 45, 12183) • p[@WIDTH <= 40] <=40 (i.e. 2, 35, 40) Reminder Some characters have to be escaped in XML because they conflict with the syntax. < < > > & &
Testing elements • “div[p]” Notice the difference with “div/p”
Positions <div> <p>bla bla</p> (1) just this should be indented <p>bla bla</p> (2) <p>bla bla</p> (3) <p>bla bla</p> (4) </div>
Functions for testing positions • position() reports on the position of the current node in the current selected list. • last() tells you the number of the last node in the current selected list.
The XSLT <xsl:template match=“div/p[position()=1]”> <p style=“margin-left: 1cm;”> <xsl:apply-templates/> </p> </xsl:template> <xsl:template match=“div/p[position()!=1]”> <p> <xsl:apply-templates/> </p> </xsl:template>
Abbreviated syntax <xsl:value-of select=“p[position()=1]”/> = <xsl:value-of select=“p[1]”/> • <xsl:value-of select=“p[position()=last()]”/> = • <xsl:value-of select=“p[last()]”/>
Examples and Exercises Example: PBE Exercise: Ex. 3