【问题标题】:How do I preserve line feeds, tabs, and spaces in data while still wrapping text?如何在仍然换行的同时保留数据中的换行符、制表符和空格?
【发布时间】:2010-09-10 08:56:51
【问题描述】:

我有 XML 中的数据,其中包含我想在输出 HTML 中保留的换行符、空格和制表符(所以我不能使用

)但我也希望这些行在已到达屏幕(所以我无法使用

)。
    

【问题讨论】:

    标签: xslt


    【解决方案1】:

    我和一位同事 (Patricia Eromosele) 提出了以下解决方案:(有更好的解决方案吗?)

     




    -template>





    来源:http://jamesjava.blogspot.com/2008/06/xsl-preserving-line-feeds-tabs-and.html

    【讨论】:

      【解决方案2】:

      真的,我会选择一个正确支持此功能的编辑器,而不是通过更多的 XML 来解决它。

      【讨论】:

      • 我使用 XSLT 将 XML 转换为 HTML,因此没有使用编辑器。
      【解决方案3】:

      不确定这是否相关,但是否没有preservespace 属性和xml 之类的?

      【讨论】:

        【解决方案4】:

        另一种表达方式是,您希望将所有空格对转换为两个不间断空格,将制表符转换为四个不间断空格,并将所有换行符转换为 <br> 元素。在 XSLT 1.0 中,我会这样做:

        <xsl:template name="replace-spaces">
          <xsl:param name="text" />
          <xsl:choose>
            <xsl:when test="contains($text, '  ')">
              <xsl:call-template name="replace-spaces">
                <xsl:with-param name="text" select="substring-before($text, '  ')"/>
              </xsl:call-template>
              <xsl:text>&#xA0;&#xA0;</xsl:text>
              <xsl:call-template name="replace-spaces">
                <xsl:with-param name="text" select="substring-before($text, '  ')" />
              </xsl:call-template>
            </xsl:when>
            <xsl:when test="contains($text, '&#x9;')">
              <xsl:call-template name="replace-spaces">
                <xsl:with-param name="text" select="substring-before($text, '&#x9;')"/>
              </xsl:call-template>
              <xsl:text>&#xA0;&#xA0;&#xA0;&#xA0;</xsl:text>
              <xsl:call-template name="replace-spaces">
                <xsl:with-param name="text" select="substring-before($text, '&#x9;')" />
              </xsl:call-template>
            </xsl:when>
            <xsl:when test="contains($text, '&#xA;')">
              <xsl:call-template name="replace-spaces">
                <xsl:with-param name="text" select="substring-before($text, '&#xA;')" />
              </xsl:call-template>
              <br />
              <xsl:call-template name="replace-spaces">
                <xsl:with-param name="text" select="substring-after($text, '&#xA;')" />
              </xsl:call-template>
            </xsl:when>
            <xsl:otherwise>
              <xsl:value-of select="$text" />
            </xsl:otherwise>
          </xsl:choose>
        </xsl:template>
        

        不能使用尾递归有点麻烦,但除非文本非常长,否则应该不是真正的问题。

        XSLT 2.0 解决方案将使用 &lt;xsl:analyze-string&gt;

        【讨论】:

        • 更正:您的代码中有两个 substring-before 应该是 substring-after。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-12
        • 2019-03-17
        • 1970-01-01
        • 2011-09-15
        • 2019-11-20
        相关资源
        最近更新 更多