如何在Xslt转换后阻止输出中出现不需要的空格

时间:2009-09-23 16:23:15

标签: xml xslt

我正在使用VS2008来编写和测试xsl转换。输出包含不需要的空白区域,如此简化示例所示:

输入:

<?xml version="1.0" encoding="utf-8" ?>
<envelope>
  <header>
    <head id="1" text="Heading1"/>
  </header>
  <body>
    <message>
      <items>
        <item id="1" Color="Red"/>
        <item id="2" Color="Green"/>
        <item id="3" Color="Blue"/>
        <item id="4" Color="Purple"/>
      </items>
    </message>
  </body>
</envelope>

转型:

<?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="xml" indent="yes"/>

  <xsl:template match="message">
    <xsl:element name="Colors">
      <xsl:apply-templates select="items/item" />
    </xsl:element>
  </xsl:template>

  <xsl:template match="items/item">
    <xsl:element name="Color">
      <xsl:value-of select="@Color"/>
    </xsl:element>
  </xsl:template>

</xsl:stylesheet>

输出:

<?xml version="1.0" encoding="utf-8"?>




        <Colors><Color>Red</Color><Color>Green</Color><Color>Blue</Color><Color>Purple</Color></Colors>

虽然很难在输出中显示,但是即使我的模板不匹配,输入文件中的空格也会被发送到输出文件。这就是我想要的并期望输出看起来像:

<?xml version="1.0" encoding="utf-8"?>
<Colors>
  <Color>Red</Color>
  <Color>Green</Color>
  <Color>Blue</Color>
  <Color>Purple</Color>
</Colors>

这可能吗?我现在可能要做的是将结果加载到Xml文档中,然后再次格式化它。

1 个答案:

答案 0 :(得分:2)

要删除不需要的空格,添加此模板应该可以解决问题:

<xsl:template match="text()"/>

这意味着“忽略所有文本节点”。

对于漂亮的打印,indent元素上的output属性应该有效。我不确定为什么会被忽略,一切都在同一条线上。也许是微软的问题?