0

我试图从我的 xslt 文档中保留空格我的代码是

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 文档

<?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文件

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

我的预期输出是“Hello World”,但我目前正在获得“HelloWorld”,我们将不胜感激。

4

2 回答 2

1

或者,您可以使用

<xsl:value-of select="concat(FirstWord, ' ', SecondWord)"/>
于 2014-02-04T10:29:28.093 回答
0

错误的不是一般的空白保留。只是您的输入 XML 中一开始就没有空白字符——而且您从未在 XSLT 过程中引入任何空白字符。

空的 CDATA 部分 ( <![CDATA[]]>) 不会在输出 XML 中产生空格。

root将您的模板定义更改为:

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

编辑

<?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>

顺便说一句,保留空间是 XSLT 处理器采取的默认操作。所以,实际上你不必指定这个。

于 2014-02-04T10:26:22.573 回答