使用XSLT获得所需的输出

时间:2015-04-28 10:40:57

标签: xml xslt xslt-2.0

我有以下XML

<Name>
  <Person>
    <Car>
      <brand>Merc</brand>
    </Car>
    <Car>
      <brand>Merc</brand>
    </Car>
  </Person>
  <Person>
    <Car>
      <brand>Audi</brand>
    </Car>
  </Person>
</Name>

我想要的输出是

<People>
  <Resident>
   <Number>1</Number>
   <Vehicle>
     <CarNumber>1</CarNumber>
     <CarNumber>2</CarNumber>
  </Vehicle>
 </Resident>
 <Resident>
   <Number>2</Number>
   <Vehicle>
     <CarNumber>3</CarNumber>
   </Vehicle>
 </Resident>
</People>

请注意,CarNumber在第二位居民中为3人。

我已经关注了这个

的XSLT
<People>    
  <xsl:for-each select="Name/Person">
    <Resident>
      <Number><xsl:value-of select="position()"/></Number>
    </Resident>
    <Vehicle>
      <xsl:for-each select="Car/brand">
        <CarNumber><xsl:value-of select="position()"/><CarNumber>
      </xsl:for-each>
    </Vehicle>
 </xsl:for-each>

但我正在

<People>
<Resident>
    <Number>1</Number>
    <Vehicle>
        <CarNumber>1</CarNumber>
        <CarNumber>2</CarNumber>
    </Vehicle>
</Resident>
<Resident>
    <Number>2</Number>
    <Vehicle>
        <CarNumber>1</CarNumber>
    </Vehicle>
</Resident>

无论如何我可以使用XSLT转换它吗?

在这里,而不是3作为CarNumber,我得到1。

1 个答案:

答案 0 :(得分:0)

请尝试这种方式:

<xsl:template match="/">
    <People>    
        <xsl:for-each select="Name/Person">
            <Resident>
                <Number><xsl:number/></Number>
            </Resident>
            <Vehicle>
                <xsl:for-each select="Car">
                    <CarNumber><xsl:number level="any"/></CarNumber>
                </xsl:for-each>
            </Vehicle>
        </xsl:for-each>
    </People>   
</xsl:template>