Search code examples
c#xslt

XSL\C# - Why xsl:template add lines in output


I use xslt file to write files in text mode (xsl:output method="text").

This xslt is transform via C# code.

My xslt is like this

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:utils="urn:myExtension" exclude-result-prefixes="msxsl">
    <!-- Déclaration du format de sortie (texte) -->
    <xsl:output method="text" indent="no" />

    <!-- Modèle principal -->
    <xsl:template match="/">
        test
    </xsl:template>
</xsl:stylesheet>

The output is like this, with newline and space at end :


        test
    

My question is why newline are added to the output ? It's like if the "<xsl:template>" itself and the indent of the xslt are take into the output. Is it possible to change this ?

I don't want that tags are taken to indent text.

If I write my template like this :
<xsl:template match="/">test</xsl:template>

or like this :

    <xsl:template match="/">
        <xsl:text>test</xsl:text>
    </xsl:template>

It's ok, the result is test

But I have a lot of "<xsl:value-of select" inside text so do I have to put "<xsl:text>" each time I need ?

My C# is like this :

var xsltSettings = new XsltSettings(false, true);
var transform = new XslCompiledTransform();
transform.Load(xsltFile, xsltSettings, new XmlUrlResolver());

transform.Transform(xmlFile, outputFile);

I tried with a XmlWriter and same result

using (var writer = XmlWriter.Create(outputFile, transform.OutputSettings))
{
    transform.Transform(xmlFile, writer);
}

Hope to be clear.


Solution

  • The general rule is that text nodes in a stylesheet that consist entirely of whitespace are ignored, but whitespace which is part of a text node that also contains printable text is treated as being significant. You've already found the remedy: use xsl:text.