2011-02-04 13 views
2

経由XHTMLのタグと属性は、私はXHTMLページに次のように持って言う:スタイルの交換= XSLT

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

は、どのように私はこれを変換するに行くか:

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

答えて

2

これはようではありませんXSLTは文字列解析のための最良のツールではないので簡単ですが、それはスタイル属性の内容を得るために必要なものです。普通です。

しかし、あなたの入力の複雑さに応じて、このようなものは、(私も、できるだけ一般的なことしようとした)十分かもしれません:

<!-- 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> 
+0

+1速く正解のために。 – Flack

+0

@Flack:私が見ていることによると、あなたは少し速かったです。 :) – Tomalak

+0

@Tomalak、私はちょっと間違っていて、編集を始めました、そしてここにいるのです。 – Flack

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> 
+0

+1は良い答えです。 – Flack