I have a XSLT document that I am using to transform one XML document into another XML document. Part of the transformation takes some of the input XML, escapes it (e.g. <mytag someattribute="value"/> converts to <mytag someattribute=\"value\"/>) and then inserts it into the output XML document somewhere.
The problem that I am having is that if a tag has a namespace specified, it skips the namespace during the escaping process.
I am performing the transformation in a .NET application (Framework 4.0) using System.Xml.Xsl.XslCompiledTransform to perform the transformation. (It only supports XSLT 1.0).
My Templates
<xsl:template match="*" mode="serialize">
<xsl:text><</xsl:text>
<xsl:value-of select="name()"/>
<xsl:apply-templates select="@*" mode="serialize" />
<xsl:choose>
<xsl:when test="node()">
<xsl:text>></xsl:text>
<xsl:apply-templates mode="serialize" />
<xsl:text></</xsl:text>
<xsl:value-of select="name()"/>
<xsl:text>></xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:text> /></xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="@*" mode="serialize">
<xsl:text> </xsl:text>
<xsl:value-of select="name()"/>
<xsl:text>=\"</xsl:text>
<xsl:value-of select="."/>
<xsl:text>\"</xsl:text>
</xsl:template>
<xsl:template match="text()" mode="serialize">
<xsl:value-of select="."/>
</xsl:template>
Example Input XML
<link xmlns:xlink="http://www.w3.org/1999/xlink"
action="goto" xlink:href="http://localhost"/>
Expected Output
<link xmlns:xlink=\"http://www.w3.org/1999/xlink\" action=\"goto\" xlink:href=\"http://localhost\"/>
Actual Output
<link action=\"goto\" xlink:href=\"http://localhost\"/>
How can I change the templates so that the namespaces are output as well?
XslTransformhas been obsoleted years ago byXslCompiledTransformbut in both processors you can add extension script or objects which could employ msdn.microsoft.com/en-us/library/… or use an XmlWriter. That should give you a good XML serialization including namespaces and needed XML escaping of e.g. the ampersand. Otherwise use the XPath namespace axis if you want to find namespace info with pure XSLT/XPath 1.0. - Martin Honnennamespace::*use on how to do it with pure XSLT/XPath to output namespace declarations. If you simply want XML serialization then you can pass your node from XSLT to a .NET function taking an XPathNavigator or XPathNodeIterator and simply use theOuterXmland return that to XSLT from your .NET function (docs.microsoft.com/en-us/dotnet/standard/data/xml/…) - Martin Honnen