我有以下结构:
League
----Clubs
---------Club
-------------Players
--------------------Player
--------------------------FirstName
--------------------------Surname etc
--------------------Player
--------------------------FirstName
--------------------------Surname etc
---------Club
-------------Players
--------------------Player
--------------------------FirstName
--------------------------Surname etc
--------------------Player
--------------------------FirstName
--------------------------Surname etc
无论如何,我想在xslt转换中获得所有玩家的名字(我使用的是Biztalk映射器,所以必须坚持XSLT1)。我更喜欢使用内联xslt,而不是映射器工具,因为我转换到的XML在俱乐部没有玩家的情况下需要一个nil属性(在这种情况下只有一个俱乐部,但我也会保留这个属性以备将来使用)
以下是我尝试过的一个粗略样本:
<xsl:template name="PlayerNames">
<xsl:element name="ns0:PlayersInLeague">
<xsl:element name="ns0:Team>
<xsl:choose>
<xsl:when test="current()/*[local-name()='Players']/*[local-name()='Player']">
<xsl:for-each select="current()/*[local-name()='Players']/*[local-name()='Player']">
<xsl:element name="ns0:Player"><xsl:value-of select="current()/*[local-name()='FirstName']"/></xsl:element>
</xsl:for-each>
</xsl:when>
<xsl:otherwise>
<xsl:attribute name="xsi:nil">true</xsl:attribute>
</xsl:otherwise>
</xsl:choose>
</xsl:element>
</xsl:element>
</xsl:template>
我想要这样的输出:
玩家联盟
----团队
------Fred
------David
----团队xsi:nil=真实
----团队
------Alex
------Tom
来自的输入
<league>
<clubs>
<club name="London">
<players>
<player>
<firstname>fred</firstname>
</player>
<player>
<firstname>david</firstname>
</player>
</players>
</club>
<club name="Madrid">
<players/>
</club>
<club name="Amsterdam">
<players>
<player>
<firstname>Alex</firstname>
</player>
<player>
<firstname>Tom</firstname>
</player>
</players>
</club>
</clubs>
</league>
我不完全确定current()命令在做什么,我已经更改了很多次了,现在我不知道如何更正它——有人能帮忙吗?
在XSLT中,您通常希望使用模式匹配来区分不同的情况。在这里,你可以制作两个模板——一个用于空俱乐部,另一个用于常规俱乐部。
它很冗长,但一旦您忘记了循环,它实际上就非常清楚了。
编辑:现在,我认为如果我反向组织模板会更有意义。因此,请从下至上阅读样式表。对不起
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
<xsl:template match="player"> <!-- only display firstname contents -->
<xsl:copy>
<xsl:apply-templates select="firstname"/>
</xsl:copy>
</xsl:template>
<xsl:template match="club"> <!-- default club template -->
<team>
<xsl:apply-templates/>
</team>
</xsl:template>
<xsl:template match="club[not(players/player)]"> <!-- empty club template -->
<team>
<xsl:attribute name="nil" namespace="http://www.w3.org/2001/XMLSchema-instance">true</xsl:attribute>
</team>
</xsl:template>
<xsl:template match="/"> <!-- entry template -->
<PlayersInLeague>
<xsl:apply-templates/>
</PlayersInLeague>
</xsl:template>
</xsl:stylesheet>