Question

I am trying to keep whitespaces from my xslt document my code is

var xslCompiledTransform = new XslCompiledTransform();
xslCompiledTransform.Load( @"SimpleSpacing.xslt" );
string result;
using ( XmlReader reader = XmlReader.Create( @"SimpleSpacing.xml" ) )
            {
                using ( var stringWriter = new StringWriter() )
                {
                    using ( var htmlTextWriter = new SpawtzHtmlTextWriter( stringWriter ) )
                    {
                        xslCompiledTransform.Transform( reader, args, htmlTextWriter );
                        htmlTextWriter.Flush();
                    }
                    result =  stringWriter.ToString();
                }
            }

Xslt Document

<?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" exclude-result-prefixes="msxsl"
>
    <xsl:output method="html"/>
        <xsl:preserve-space elements="*"/>

    <xsl:template match="/">
      <xsl:apply-templates select="*"/>
    </xsl:template>

  <xsl:template match="root">
    <xsl:value-of select="FirstWord"/>&#032;<xsl:value-of select="SecondWord"/>
  </xsl:template>
</xsl:stylesheet>

Xml Document

<root>
  <FirstWord>Hello</FirstWord>
  <SecondWord>World</SecondWord>
</root>

My expected output is "Hello World" but i am currently getting "HelloWorld" and help would be greatly appreciated.

Was it helpful?

Solution 2

It is not general whitespace preservation that is at fault. It is just that there is no whitespace character in your input XML in the first place - and you never introduced any during the XSLT process.

An empty CDATA section (<![CDATA[]]>) does not produce whitespace in your output XML.

Change your root template definition to:

<xsl:template match="root">
    <xsl:value-of select="FirstWord"/>
    <xsl:text> </xsl:text>
    <xsl:value-of select="SecondWord"/>
</xsl:template>

Edit:

<?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" exclude-result-prefixes="msxsl">
 <xsl:output method="html"/>
 <xsl:preserve-space elements="*"/>

 <xsl:template match="/">
   <xsl:apply-templates/>
 </xsl:template>

 <xsl:template match="root">
   <xsl:value-of select="FirstWord"/>
   <xsl:text>&#032;</xsl:text>
   <xsl:value-of select="SecondWord"/>
 </xsl:template>

</xsl:stylesheet>

By the way, preserving space is the default action taken by the XSLT processor. So, actually you do not have to specify this.

OTHER TIPS

alternatively, you can use

<xsl:value-of select="concat(FirstWord, ' ', SecondWord)"/>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top