XSL: Avoid exporting namespace definitions to resulting XML documents

You can use the exclude-result-prefixes attribute of the xsl:stylesheet element to avoid emitting namespace prefixes into the output document: <?xml version=”1.0″ encoding=”ISO-8859-1″?> <xsl:stylesheet version=”1.0″ xmlns:xsl=”http://www.w3.org/1999/XSL/Transform” xmlns:prefix1=”http://www.something.com” exclude-result-prefixes=”prefix1″> </xsl:stylesheet> To suppress multiple namespaces from the output document specify them separated by whitespace: exclude-result-prefixes=”prefix1 prefix2 prefix3″ From the XSLT specification: When a stylesheet uses a namespace declaration … Read more

XSLT – remove whitespace from template

In XSLT, white-space is preserved by default, since it can very well be relevant data. The best way to prevent unwanted white-space in the output is not to create it in the first place. Don’t do: <xsl:template match=”foo”> foo </xsl:template> because that’s “\n··foo\n”, from the processor’s point of view. Rather do <xsl:template match=”foo”> <xsl:text>foo</xsl:text> </xsl:template> … Read more

How to use XSLT to create distinct values

An XSLT 1.0 solution that uses key and the generate-id() function to get distinct values: <?xml version=”1.0″ encoding=”UTF-8″?> <xsl:stylesheet version=”1.0″ xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”> <xsl:output method=”xml” encoding=”UTF-8″ indent=”yes”/> <xsl:key name=”product” match=”/items/item/products/product/text()” use=”.” /> <xsl:template match=”https://stackoverflow.com/”> <xsl:for-each select=”/items/item/products/product/text()[generate-id() = generate-id(key(‘product’,.)[1])]”> <li> <xsl:value-of select=”.”/> </li> </xsl:for-each> </xsl:template> </xsl:stylesheet>

XSL for-each: how to detect last node?

If you’re using XSLT 2.0, the canonical answer to your problem is <xsl:value-of select=”GroupsServed” separator=”, ” /> On XSLT 1.0, the somewhat CPU-expensive approach to finding the last element in a node-set is <xsl:if test=”position() = last()” />

How to save newlines in XML attribute?

In a compliant DOM API there is nothing you need to do. Simply save actual newline characters to the attribute, the API will encode them correctly on its own (see Canonical XML spec, section 5.2). If you do your own encoding (i.e. replacing \n with &#10; before saving the attribute value), the API will encode … Read more