XML technologies / XSLT / XSLT Kochbuch / Selecting and traversing / Selecting everything except a particular element
(Excerpt from "XSLT Kochbuch" by Sal Mangano)
Problem
You want to select all elements in a context except those you wish to omit.
Solution
The best way to select all but one particular element is:
<xsl:apply-templates select="*[not(self::element-to-ignore)]"/>To use iteration, specify:
<xsl:for-each select="*[not(self::element-to-ignore)]">
...
</xsl:for-each>Discussion
When XSLT beginners need to select all but a particular element, they may first try a construct like this:
<xsl:apply-templates select="*[name( ) != 'element-to-ignore']"/>This code works in many cases but may cause trouble if the document uses Namespaces. Remember that name( ) returns the QName of the node: The namespace prefix concatenated with the local part of the name. However, nothing forces an XML author to use a particular prefix:
<!--Dies schlägt fehl, falls der Autor beschließt, SALES:product anstelle von sales:product einzusetzen -->
<xsl:apply-templates select="*[name( ) != 'sales:product']"/>Alternatively, you could use local-name( ). However, this would ignore elements with that local name in every namespace, which is probably not what you intended.
This suggestion applies only to elements, not attributes. To select all but a particular attribute, use local-name( ). The self axis refers only to elements when applied to a name. In other words, use <xsl:copy-of select="@*[local-name( ) != 'ignored-attribute']" /> rather than <xsl:copy-of select="@*[not(self::ignored-attribute)]" />.
Finally, to avoid confusion, selecting all elements except one is different from selecting all instances of an element except one. The latter case appears in an example discussed earlier in this chapter:
<xsl:apply-templates select="*[generate-id( ) != generate-id($node-to-ignore)]"/>See also
Jeni Tennison’s book XSLT and XPath on the Edge (M&T Books, 2001) explains in detail when name( ) and local-name( ) should and should not be used.
Copyright © 2006 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from "XSLT Kochbuch" is subject to the same terms as the printed edition: the work and all its parts are protected by copyright. All rights are reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O'Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de