访问XML中的不同节点

时间:2018-11-29 15:04:08

标签: xml xslt

我为标题不好对不起。我正在尝试为此XML开发XSLT文件:

<game>
    <character>
        <name>Rambo</name>
        <attribute>
            <strength>15</strength>
            <stamina>10</stamina>
            <agility>24</agility>
            <health>100</health>
        </attribute>
    </character>

    <character>
        <name>Sonic X</name>
        <attribute>
            <strength>10</strength>
            <stamina>15</stamina>
            <agility>10</agility>
            <health>100</health>
        </attribute>
    </character>

    <costume>
        <name>Armor</name>
        <attribute>
            <agility>-15</agility>
            <health>50</health>
        </attribute>
    </costume>

    <costume>
        <name>Boots</name>
        <attribute>
            <agility>75</agility>
        </attribute>
    </costume>
</game>

我的XSLT应该做什么:对于角色和服装的每种组合,都需要计算组合的敏捷性。例如。 (字符敏捷性)+(服装敏捷性)。

输出应如下所示:

<boosted_agility>
    <result>
       <character> Character name (e.g. Rambo) </character>
       <costume> Costume name (e.g. Armor) </costume>
       <agility> New agility value (E.g. 24 + (-15) = 9) </agility>
    </result>
    ..........    
<boosted_agility>

我想做这样的事情(下面的破损代码):

<xsl:template match="/">
        <boosted_agility> 
            <xsl:for-each select="game/character and game/costume">
                <result>
                    <character> <xsl:value-of select="character.name"/> </character>
                    <costume><xsl:value-of select="costume.name"/></costume>
                    <agility> <xsl:value-of select="costume.attribute.agility"/> + <xsl:value-of select="character.attribute.agility"/></agility>
                </result>
            </xsl:for-each>
        </boosted_agility>
    </xsl:template>

提前谢谢!

1 个答案:

答案 0 :(得分:1)

就像@ michael.hor257k一样,您需要两个xsl:for-each,但是您还想使用xsl:variable来存储costumes和当前character,因为它们不在范围。

这应该有效:

<xsl:template match="/">
    <boosted_agility> 
        <xsl:variable name="costumes" select="game/costume"/>
        <xsl:for-each select="game/character">
            <xsl:variable name="character" select="."/>
            <xsl:for-each select="$costumes">
                <result>
                    <character><xsl:value-of select="$character/name"/></character>
                    <costume><xsl:value-of select="name"/></costume>
                    <agility><xsl:value-of select="$character/attribute/agility + attribute/agility"/></agility>
                </result>
            </xsl:for-each>
        </xsl:for-each>
    </boosted_agility>
</xsl:template>