html - 如何拆分文本并保留 HTML 标记 (XSLT 2.0)

标签 html xslt xslt-2.0

我有一个包含描述节点的 xml:

<config>
  <desc>A <b>first</b> sentence here. The second sentence with some link <a href="myurl">The link</a>. The <u>third</u> one.</desc>
</config>

我正在尝试使用点作为分隔符来拆分句子,但同时在 HTML 输出中保留最终的 HTML 标记。 到目前为止,我拥有的是一个拆分描述的模板,但由于 normalize-space 和 substring-before 函数,HTML 标记在输出中丢失了。 我当前的模板如下:

<xsl:template name="output-tokens">
  <xsl:param name="sourceText" />

  <!-- Force a . at the end -->
  <xsl:variable name="newlist" select="concat(normalize-space($sourceText), ' ')" />
  <!-- Check if we have really a point at the end -->
  <xsl:choose>
    <xsl:when test ="contains($newlist, '.')">
      <!-- Find the first . in the string -->
      <xsl:variable name="first" select="substring-before($newlist, '.')" />

      <!-- Get the remaining text -->
      <xsl:variable name="remaining" select="substring-after($newlist, '.')" />
      <!-- Check if our string is not in fact a . or an empty string -->
      <xsl:if test="normalize-space($first)!='.' and normalize-space($first)!=''">
        <p><xsl:value-of select="normalize-space($first)" />.</p>
      </xsl:if>
      <!-- Recursively apply the template for the remaining text -->
      <xsl:if test="$remaining">
        <xsl:call-template name="output-tokens">
          <xsl:with-param name="sourceText" select="$remaining" />
        </xsl:call-template>
      </xsl:if>
    </xsl:when>
    <!--If no . was found -->
    <xsl:otherwise>
      <p>
        <!-- If the string does not contains a . then display the text but avoid 
           displaying empty strings 
         -->
        <xsl:if test="normalize-space($sourceText)!=''">
          <xsl:value-of select="normalize-space($sourceText)" />.
        </xsl:if>
      </p>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

我按以下方式使用它:

<xsl:template match="config">
  <xsl:call-template name="output-tokens">
       <xsl:with-param name="sourceText" select="desc" />
  </xsl:call-template>
</xsl:template>

预期的输出是:

<p>A <b>first</b> sentence here.</p>
<p>The second sentence with some link <a href="myurl">The link</a>.</p>
<p>The <u>third</u> one.</p>

最佳答案

一个好问题,但不是一个容易解决的问题。当然,尤其是如果您使用的是 XSLT 1.0(如果是这种情况,您确实需要告诉我们)。

我见过两种解决问题的方法。两者都涉及将其分解为更小的问题。

第一种方法是将标记转换为文本(例如将 <b>first</b> 替换为 [b]first[/b] ),然后使用文本操作操作(xsl:analyze-string)将其拆分为句子,然后在其中重构标记句子。

第二种方法(我个人更喜欢)是将文本分隔符转换为标记(将“.”转换为 <stop/> ),然后使用位置分组技术(通常 < xsl:for-each-group group-ending-with="stop"/> 将句子转换为段落。)

关于html - 如何拆分文本并保留 HTML 标记 (XSLT 2.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6420736/

相关文章:

css - 使用百分比值填充 flexbox 元素

php - 将 HTML-PHP 表导出/下载到 Excel 文件

html - 图片上的文字

java - 使用 XSLT 删除 PrettyPrint

xml - 在 xslt 中添加前导零记录

javascript - 如何使用 Jquery 中的切换类更改内部 html 内容?

xslt - WiX - 根据环境将编译后的 web.config 复制到网站根目录

xslt - 使用 xslt 构建 django 模板文件

c# - 如何使用撒克逊将文档类型参数传递给 xslt?

xml - 有什么方法可以在 XSLT 期间从 XSD 复制 VALUE(架构感知 XSLT 2.0 ala 架构验证后信息集))?