xml - 如何用替换br标签 XSL模板中的标签?

标签 xml xslt xpath replace linefeed

假设我有一个简单的XML文件:

<data>
  <text>Hello world!&lt;br&gt;Nice to see you all!&lt;br&gt;Goodbye!</text>
</data>


现在我想将所有&lt;br&gt;字符串替换为&#10;字符串,因此结果应为:

<transformed>
  <text>Hello world!&#10;Nice to see you all!&#10;Goodbye!</text>
</transformed>


我该怎么做呢?

XSL替换功能易于实现(例如,在http://geekswithblogs.net/Erik/archive/2008/04/01/120915.aspx中),但棘手的部分是让XSL转换器输出这些&#10;字符串。

完美的答案将是可以解决问题的XSL模板。

最佳答案

用:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/data">
    <transformed>
      <text>
        <xsl:call-template name="string-replace-all">
          <xsl:with-param name="text" select="text" />
          <xsl:with-param name="replace">&lt;br&gt;</xsl:with-param>
          <xsl:with-param name="by">&amp;#10;</xsl:with-param>
        </xsl:call-template>
      </text>
    </transformed>
  </xsl:template>

  <xsl:template name="string-replace-all">
    <xsl:param name="text" />
    <xsl:param name="replace" />
    <xsl:param name="by" />
    <xsl:choose>
      <xsl:when test="contains($text, $replace)">
        <xsl:value-of select="substring-before($text, $replace)" />
        <xsl:value-of select="$by" disable-output-escaping="yes" />
        <xsl:call-template name="string-replace-all">
          <xsl:with-param name="text" select="substring-after($text,$replace)" />
          <xsl:with-param name="replace" select="$replace" />
          <xsl:with-param name="by" select="$by" />
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$text" />
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

</xsl:stylesheet>


输出:

<transformed>
  <text>Hello world!&#10;Nice to see you all!&#10;Goodbye!</text>
</transformed>


注意!:

disable-output-escaping属性设置为yes

关于xml - 如何用替换br标签 XSL模板中的标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9079948/

相关文章:

c# - 使用 linq 与 xmlDocument 从 XML 字符串中提取数据

xml - *您*如何在 Web 应用程序的世界中使用 XML?

xml - XSD 正则表达式 : Why is this not working when parsed into HTML with an XSLT?

java - 无法通过 Selenium 和 Java 在 https ://spicejet. com 中选择出发日期

java - Android XML RSA,错误 : java. security.InvalidKeyException:传递给 RSA 的未知 key 类型

xml - 使用 AngularJS 返回 xml 的跨域 ajax 请求

xml - XSLT 多个节点同名同级

html - 使用 xsl :element tag for html transformation

xml - XSLT 中的双斜线

java - 在 XPath 1.0 中将整数转换为 double