【发布时间】:2011-06-21 15:54:21
【问题描述】:
假设我在 XHTML 页面中有以下内容:
<span style="color:#555555; font-style:italic">some text</span>
我将如何将其转换为:
<span style="color:#555555;"><em>some text</em></span>
【问题讨论】:
假设我在 XHTML 页面中有以下内容:
<span style="color:#555555; font-style:italic">some text</span>
我将如何将其转换为:
<span style="color:#555555;"><em>some text</em></span>
【问题讨论】:
这并不像看起来那么容易,因为 XSLT 不是字符串解析的最佳工具 - 但这正是您通常需要获取样式属性 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>
【讨论】:
contains(translate(@style。你忘记了@ 符号。
只是为了好玩,一个更通用的 XSLT 2.0 解决方案(可以优化):
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template
match="span[tokenize(@style,';')[
matches(.,'\p{Z}*font\-style\p{Z}*:\p{Z}*italic\p{Z}*')
]]">
<xsl:copy>
<xsl:apply-templates select="@* except @style"/>
<xsl:attribute
name="style"
select=
"tokenize(@style,';')[not(
matches(.,'\p{Z}*font\-style\p{Z}*:\p{Z}*italic\p{Z}*')
)]"
separator=";"/>
<em>
<xsl:apply-templates select="node()"/>
</em>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
输出:
<span style="color:#555555"><em>some text</em></span>
【讨论】: