【问题标题】:Passing spaces to template through with-param in XSLT通过 XSLT 中的 with-param 将空格传递给模板
【发布时间】:2013-09-27 14:15:08
【问题描述】:

我正在尝试将 XML 文档转换为一些纯文本代码输出,并希望有适当的缩进。我没有找到任何好的信息,我开始尝试了一下。

目前我正在尝试让 with-param 根据它应该使用的缩进将空格传递给模板。

<xsl:apply-templates select="foo">
  <xsl:with-param name="indent">  </xsl:with-param>
</xsl:apply-templates>

只有一个问题...如果参数仅包含空格,则空格不会传递!拥有像字符这样的其他东西可以同时传递前导和尾随空格,但只要我只传递空格,它就会更改为空字符串。

<xsl:apply-templates select="foo">
  <xsl:with-param name="indent">  a </xsl:with-param>
</xsl:apply-templates>

这是预期的行为吗?

我在 Linux 上使用 xsltproc 来运行转换。

让我知道我可以提供哪些更多信息。感谢您的帮助!

【问题讨论】:

    标签: xml xslt code-generation indentation


    【解决方案1】:

    我会简单地使用&lt;xsl:with-param name="indent" select="' '"/&gt;

    如果你想传递xsl:with-param里面的值,那么你需要使用

    <xsl:with-param name="indent">
      <xsl:text>  </xsl:text>
    </xsl:with-param>
    

    <xsl:with-param name="indent" xml:space="preserve">  </xsl:with-param>
    

    【讨论】:

    • 谢谢马丁!使用 xsl:text 有效,但使用 xml:space 的第二个建议没有任何区别。不清楚为什么不。
    • 如何传递$indent 值以及select 属性内的另外两个空格?
    • 自己找到的:concat(' ', $indent)
    【解决方案2】:

    不要将您的字符串作为 &lt;xsl:with-param&gt; 元素的文本节点,而是将其作为 select 属性传递。

    例如,以下 XSLT 样式表:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output method="text"/>
    
      <xsl:template match="/">
    
        <!-- With whitespace only. -->
        <xsl:apply-templates select="foo">
          <xsl:with-param name="indent" select=" '   ' "/>
        </xsl:apply-templates>
    
        <!-- Carriage return. -->    
        <xsl:text>&#xd;</xsl:text>
    
        <!-- With leading and trailing whitespace. -->
        <xsl:apply-templates select="foo">
          <xsl:with-param name="indent" select=" '  b  ' "/>
        </xsl:apply-templates>
      </xsl:template>
    
      <xsl:template match="foo">
        <xsl:param name="indent"/>
    
        <xsl:text>$</xsl:text>
        <xsl:value-of select="$indent"/>
        <xsl:text>$</xsl:text>    
      </xsl:template>
    
    </xsl:stylesheet>
    

    应用于此输入 XML 时:

    <foo>
      Bar
    </foo>
    

    产生以下输出:

    $   $
    $  b  $
    

    【讨论】:

    • 感谢这个很好的例子!
    猜你喜欢
    • 2017-07-18
    • 1970-01-01
    • 2013-09-15
    • 1970-01-01
    • 2017-05-07
    • 2021-03-29
    • 2018-05-26
    • 2016-08-27
    • 2010-12-04
    相关资源
    最近更新 更多