我有以下XML
<ROOT>
<COUNTRY Name="Ukraine">
<CITY>
<POPULATION>1427000</POPULATION>
<NAME>Kharkov</NAME>
<SQUARE>310 km2</SQUARE>
</CITY>
<CITY>
<POPULATION>2758000</POPULATION>
<NAME>Kiev</NAME>
<SQUARE>839 km2</SQUARE>
</CITY>
</COUNTRY>
<COUNTRY Name="England">
<CITY>
<POPULATION>7000000</POPULATION>
<NAME>London</NAME>
<SQUARE>1579 km2</SQUARE>
</CITY>
</COUNTRY>
</ROOT>
我需要使用XSLT并获得这样的结果
<ROOT>
<CITY Name="...", Population="...", Square="...", Country="..." />
</ROOT>
我已经编写了这个XSLT的一部分,但它只适用于一个COUNTRY
<xsl:template match="COUNTRY">
<ROOT>
<CITY>
<xsl:attribute name="Name">
<xsl:value-of select="CITY/NAME"/>, Population:<xsl:value-of select="CITY/POPULATION"/>, Square:<xsl:value-of select="CITY/SQUARE"/>, Country:<xsl:value-of select="@Name"/>
</xsl:attribute>
</CITY>
</ROOT>
</xsl:template>
我不知道它应该如何适用于少数几个国家和城市。我是XSLT的新手,所以我需要你的帮助。
答案 0 :(得分:0)
您需要遍历每个CITY。以下XSLT应该完成这项工作:
<xsl:template match="/ROOT">
<ROOT>
<xsl:for-each select="COUNTRY/CITY">
<CITY>
<xsl:attribute name="Name"><xsl:value-of select="NAME"/></xsl:attribute>
<xsl:attribute name="Population"><xsl:value-of select="POPULATION"/></xsl:attribute>
<xsl:attribute name="Square"><xsl:value-of select="SQUARE"/></xsl:attribute>
<xsl:attribute name="Country"><xsl:value-of select="../@Name"/></xsl:attribute>
</CITY>
</xsl:for-each>
</ROOT>
</xsl:template>
注意../@Name
的用法,它表示父元素(COUNTRY)的Name
属性。
示例结果:
<?xml version="1.0" encoding="UTF-8"?>
<ROOT>
<CITY Name="Kharkov" Population="1427000" Square="310 km2" Country="Ukraine"/>
<CITY Name="Kiev" Population="2758000" Square="839 km2" Country="Ukraine"/>
<CITY Name="London" Population="7000000" Square="1579 km2" Country="England"/>
</ROOT>