xsl检索其他属性值并将值附加到一个属性中

时间:2011-08-15 18:41:19

标签: css xml xslt xpath

开始:

<test style="font:2px;color:#FFFFFF" bgcolor="#CCCCCC" TOPMARGIN="5">style</test>

使用XSLT / XPATH,我从文档中复制了所有内容

<xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>

但我不确定如何使用XSLT / XPATH获得此结果:

<test style="background-color:#CCCCCC; margin-top:1;font:2px;color:#FFFFFF">style</test>

我想我在XPATH失败了。这是我尝试检索bgColor:

<xsl:template match="@bgColor">
 <xsl:attribute name="style">
   <xsl:text>background-color:</xsl:text>
   <xsl:value-of select="."/>
   <xsl:text>;</xsl:text>
   <xsl:value-of select="../@style"/>
 </xsl:attribute>
</xsl:template>

不幸的是,在原始文档中的bgColor之后放置样式时,即使这样也会中断。如何将这些已弃用的属性值附加到一个内联样式属性?

2 个答案:

答案 0 :(得分:1)

此转化

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/*">
  <test style="{@style};background-color:{@bgcolor};margin-top:{@TOPMARGIN}">
   <xsl:value-of select="."/>
  </test>
 </xsl:template>
</xsl:stylesheet>

应用于提供的XML文档

<test style="font:2px;color:#FFFFFF"
      bgcolor="#CCCCCC" TOPMARGIN="5">style</test>

生成想要的正确结果

<test style="font:2px;color:#FFFFFF;background-color:#CCCCCC;margin-top:5">style</test>

解释:使用 AVT

答案 1 :(得分:0)

可能不是最好的方式,但它有效:

<xsl:template match="test">
    <xsl:element name="{name()}">
        <xsl:apply-templates select="@*[name() != 'bgcolor']"/>   
    </xsl:element>
</xsl:template>    

<xsl:template match="@*">
    <xsl:copy/>
</xsl:template>

<xsl:template match="@style">
    <xsl:attribute name="style">
        <xsl:value-of select="."/>
        <xsl:text>;background-color:</xsl:text>
        <xsl:value-of select="../@bgcolor"/>
    </xsl:attribute>
</xsl:template>