【发布时间】:2011-06-21 16:34:54
【问题描述】:
这是this question的后续。
我在一个文档中有几个<span> 标记,其中有几个分号分隔的样式属性。现在我有 3 个特定的样式属性,我正在寻找将其转换为标签。只要样式属性仅包含三个样式属性之一,在上面的示例中都可以正常工作。如果跨度有更多,我会得到一个模棱两可的规则匹配。
我要查找的三个样式属性是font-style:italic、font-weight:600 和text-decoration:underline,应将它们从样式属性中移除并分别转换为<em>、<strong> 和<u> .
这是我当前的 XSLT:
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="span[
contains(translate(@style, ' ', ''), 'font-style:italic')
]">
<xsl:copy>
<xsl:attribute name="style">
<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>
<xsl:template match="span[
contains(translate(@style, ' ', ''), 'font-weight:600')
]">
<xsl:copy>
<xsl:attribute name="style">
<xsl:value-of select="substring-before(@style, ' font-weight')"/>
<xsl:value-of select="substring-after(@style, '600;')"/>
</xsl:attribute>
<strong>
<xsl:apply-templates select="node()"/>
</strong>
</xsl:copy>
</xsl:template>
<xsl:template match="span[
contains(translate(@style, ' ', ''), 'text-decoration:underline')
]">
<xsl:copy>
<xsl:attribute name="style">
<xsl:value-of select="substring-before(@style, ' text-decoration')"/>
<xsl:value-of select="substring-after(@style, 'underline;')"/>
</xsl:attribute>
<u>
<xsl:apply-templates select="node()"/>
</u>
</xsl:copy>
</xsl:template>
这将生成不明确的规则警告在包含多个所列属性的某些元素上无法正常工作。
输入示例:
<span style=" text-decoration: underline; font-weight:600; color:#555555">some text</span>
转化为:
<span style=" font-weight:600; color:#555555"><u>some text</u></span>
当期望的结果是:
<span style="color:#555555"><b><u>some text</u></b></span>
如何解决此问题的不明确规则匹配?
提前致谢
更新:
如果我将每个模板上的 priorty 设置为降序值,并在第一次 XSLT 运行的输出上再次运行 XSLT,一切都会按预期工作。必须有一种比通过两次转换更简单的方法。有什么想法吗?
正如 Alejandro 和 Tomalak 所建议的,将 CSS 类的 style 属性替换为 class 属性也是一种选择。
【问题讨论】:
-
好问题,+1。有关完整的 XSLT 1.0 解决方案,请参阅我的答案。 :)
-
我想知道:您不应该将
style翻译成一个CSS 类(或几个CSS 类),而不是<u>和<b>元素吗? -
+1 我很高兴回答这个问题,除了我和 Tomalak 一起讨论使用 CSS 样式表而不是内联 @style 和语义标记而不是样式标记。