Замена style = атрибутов тегами в XHTML через XSLT - PullRequest
2 голосов
/ 05 февраля 2011

Скажем, у меня на странице XHTML есть следующее:

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

Как мне преобразовать это в:

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

Ответы [ 2 ]

2 голосов
/ 05 февраля 2011

Просто для удовольствия, более общие решения 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>
2 голосов
/ 05 февраля 2011

Это не так просто, как кажется, так как 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>
...