使用xslt树明智地获取xml属性值

时间:2013-01-28 13:14:09

标签: xslt

这是我的xml文件:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="try.xsl"?>
<oneday>
    <team1 id="1" team="India">
        <team2 id="2" team="gujarat">
            <team3 id="3" team="guj11"></team3>
        </team2>
    </team1>
</oneday>

这是我的xsl文件:

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

<xsl:template match="*">
        <xsl:value-of select="local-name()"/>

        <xsl:apply-templates/>
    </xsl:template>

    <xsl:template match="text()[normalize-space(.)]">
        <xsl:value-of select="concat(':', .)"/>
    </xsl:template>
</xsl:stylesheet>

这是我的输出:

oneday
    team1
        team2
            team3

但我想输出这样的东西:

oneday
    team1:India
        team2:Gujarat
            team3:Guj11

1 个答案:

答案 0 :(得分:0)

这是怎么回事:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" />

  <xsl:template match="*">
    <xsl:apply-templates select="ancestor::*" mode="spacing" />

    <xsl:value-of select="local-name()"/>
    <xsl:if test="@team">
      <xsl:value-of select="concat(':', @team)"/>
    </xsl:if>
    <xsl:text>&#xA;</xsl:text>

    <xsl:apply-templates select="*" />
  </xsl:template>

  <xsl:template match="*" mode="spacing">
    <xsl:text>    </xsl:text>
  </xsl:template>
</xsl:stylesheet>

在样本XML上运行时,会产生:

oneday
    team1:India
        team2:gujarat
            team3:guj11

在稍微复杂的XML上运行时:

<oneday>
  <team1 id="1" team="India">
    <team2 id="2" team="gujarat">
      <team3 id="3" team="guj11"></team3>
    </team2>
    <team6 team="Mumbai" />
  </team1>
  <team4 team="France">
    <team5 team="Paris" />
  </team4>
</oneday>

它产生:

oneday
    team1:India
        team2:gujarat
            team3:guj11
        team6:Mumbai
    team4:France
        team5:Paris