首页 > 解决方案 > 如何在 XSLT 中聚合值?

问题描述

这是我的 xml:

<countries>
   <country>
      <name> .....</name>
      <capital>....</capital>
      <continent>....</continent>
   </country>
   .
   .
   .(a lot of countries)..
<countries>

我创建了一个包含 2 列(使用 xslt)的 html 表,代表每个国家/地区的名称和首都。但是现在我想为每个大陆创建一个表,每个表都包含属于该大陆的所有国家的列表,我不知道如何进行!感谢您的帮助!这是我的 XSLT 的快速视图:

<table border="3" width="100%" align="center">
<tr>
    <th>Name</th>
    <th>Capital</th>
</tr>

<xsl:for-each select="countries/country">
<tr>
<td >
    <xsl:value-of select="name"/>
</td>
<td>
<xsl:value-of select="capital"/>
</td>
</tr>
    </xsl:for-each>

标签: xmlxsltxpathxslt-1.0

解决方案


试试这个XSLT 1.0

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output indent="yes"/>

    <xsl:key name="Continent" match="country" use="continent"/>

    <xsl:template match="countries">
        <countries>
            <xsl:for-each
                select="//country[generate-id(.) = generate-id(key('Continent', continent)[1])]">
                <continent><xsl:value-of select="continent"/></continent>
                <table border="3" width="100%" align="center">
                    <tr>
                        <th>Name</th>
                        <th>Capital</th>
                    </tr>

                    <xsl:for-each select="key('Continent', continent)">
                        <tr>
                            <td >
                                <xsl:value-of select="name"/>
                            </td>
                            <td>
                                <xsl:value-of select="capital"/>
                            </td>
                        </tr>
                    </xsl:for-each>

                </table>
            </xsl:for-each>
            </countries>
    </xsl:template>
</xsl:stylesheet>

XSLT 1.0请参阅https://xsltfiddle.liberty-development.net/naZXVEE上的转换

XSLT 2.0请参阅https://xsltfiddle.liberty-development.net/naZXVEE/1上的转换


推荐阅读