【问题标题】:Replacing style= attributes with tags in XHTML via XSLT通过 XSLT 用 XHTML 中的标签替换 style= 属性
【发布时间】: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>

【问题讨论】:

    标签: xslt xhtml transform


    【解决方案1】:

    这并不像看起来那么容易,因为 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>
    

    【讨论】:

    • @Flack:据我所见,你的速度有点快。 :)
    • @Tomalak,我有点错了,开始编辑,你来了。顺便说一句,contains(translate(@style。你忘记了@ 符号。
    • 这是一个很好的开始。谢谢您的帮助!当然,在这个 XSLT 表中我需要做很多更复杂的事情,但这让我找到了正确的方向!
    • @Tomalak 和@Flack:我刚刚发布了一个后续问题。如果您愿意为我的 XSLT n00b 提供更多帮助,请继续努力 :) stackoverflow.com/questions/4903860/…
    【解决方案2】:

    只是为了好玩,一个更通用的 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>
    

    【讨论】:

      猜你喜欢
      • 2011-06-21
      • 1970-01-01
      • 1970-01-01
      • 2011-10-11
      • 1970-01-01
      • 2013-06-29
      • 2012-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多