2010-05-03 98 views
1

假设我得到了下面的XML文件:设置属性通过XSL所有子元素:选择

<?xml version="1.0" encoding="ISO-8859-1" ?> 
<MyCarShop> 
    <Car gender="Boy"> 
     <Door>Lamborghini</Door> 
     <Key>Skull</Key> 
    </Car> 
    <Car gender="Girl"> 
     <Door>Normal</Door> 
     <Key>Princess</Key> 
    </Car> 
</MyCarShop> 

我想执行变换所以XML看起来是这样的:

<?xml version="1.0" encoding="ISO-8859-1" ?> 
<MyCarShop> 
    <Car gender="Boy"> 
     <Door color="blue">Lamborghini</Door> 
     <Key color="blue">Skull</Key> 
    </Car> 
    <Car gender="Girl"> 
     <Door color="red">Normal</Door> 
     <Key color="red">Princess</Key> 
    </Car> 
</MyCarShop> 

所以我想根据性别信息添加属于Car的每个子元素的颜色。

我想出了这个XSLT,但它不工作:

<?xml version="1.0" encoding="utf-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" 
> 
    <xsl:output method="xml" indent="yes"/> 

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

    <xsl:template match="/"> 
    <xsl:element name="MyCarShop"> 
     <xsl:attribute name="version">1.0</xsl:attribute> 
     <xsl:apply-templates/> 
    </xsl:element> 
    </xsl:template> 

    <xsl:template match="Car"> 
    <xsl:element name="Car"> 
     <xsl:apply-templates/> 
    </xsl:element> 
    </xsl:template> 

    <xsl:template match="Door"> 
    <xsl:element name="Door"> 
      <xsl:attribute name="ViewSideIndicator"> 
     <xsl:choose> 
      <xsl:when test="gender = 'Boy' ">Front</xsl:when> 
      <xsl:when test="gender = 'Girl ">Front</xsl:when> 
     </xsl:choose> 
    </xsl:attribute> 
     </xsl:element> 
    </xsl:template> 

     <xsl:template match="Key"> 
    <xsl:element name="Key"> 
     <xsl:apply-templates/> 
      </xsl:element> 
    </xsl:template> 

    </xsl:stylesheet> 

有谁知道什么可能是错误的?

再次感谢!

回答

2

我将测试中的值更改为../@gender,现在该模板根据Car的'gender'属性的值为'Door'节点添加颜色属性。 ..表示'获得父节点'。 @表示'获取属性的值'。

<xsl:template match="Door"> 
<xsl:element name="Door"> 
    <xsl:attribute name="color"> 
    <xsl:choose> 
     <xsl:when test="../@gender = 'Boy' ">Red</xsl:when> 
     <xsl:when test="../@gender = 'Girl' ">Green</xsl:when> 
    </xsl:choose> 
    </xsl:attribute> 
</xsl:element> 

你应该做的“钥匙”模板相同(或通过提取成独立named template更好的重用“选择”的代码)。

希望这会有所帮助。

+0

首先感谢您重播,但此解决方案无效。我的输出现在是“”但我想要这个“兰博基尼 Camal 2010-05-03 11:53:03

+0

我现在知道了!我只是在前面添加了 :) – Camal 2010-05-03 11:59:37