通过 XSLT 用 XHTML 中的标签替换 style= 属性

2024-03-31

假设我在 XHTML 页面中有以下内容:

<span style="color:#555555; font-style:italic">some text</span>

我将如何将其转换为:

<span style="color:#555555;"><em>some text</em></span>

这并不像看起来那么容易,因为 XSLT 不是字符串解析的最佳工具 - 但这正是获取 style 属性的内容所需要的right一般而言。

但是,根据您输入的复杂性,类似这样的内容可能就足够了(不过,我尝试尽可能通用):

<!-- it's a good idea to build most XSLT around the identity template -->
<xsl:template match="node()|@*">
  <xsl:copy>
    <xsl:apply-templates select="node()|@*" />
  </xsl:copy>
</xsl:template>

<!-- specific templates over general ones with complex if/choose inside -->
<xsl:template match="span[
  contains(translate(@style, ' ', ''), 'font-style:italic')
]">
  <xsl:copy>
    <xsl:copy-of select="@*" />
    <xsl:attribute name="style">
      <!-- this is pretty assumptious - might work, might break,
           depending on how complex the @style value is -->
      <xsl:value-of select="substring-before(@style, 'font-style')" />
      <xsl:value-of select="substring-after(@style, 'italic')" />
    </xsl:attribute>
    <em>
      <xsl:apply-templates select="node()" />
    </em>
  </xsl:copy>
</xsl:template>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 XSLT 用 XHTML 中的标签替换 style= 属性 的相关文章

随机推荐