You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

XSL 1.0循环内分组:将空白country节点归至上对应国家节点

XSL 1.0 实现空白country节点归组并生成表格

示例XML输入

<root>
  <item country="China">
    <name>Beijing</name>
  </item>
  <item country="">
    <name>Shanghai</name>
  </item>
  <item country="">
    <name>Guangzhou</name>
  </item>
  <item country="USA">
    <name>New York</name>
  </item>
  <item country="">
    <name>Los Angeles</name>
  </item>
</root>

核心解决思路

XSL 1.0没有group-adjacent功能,所以用**键(key)**来关联空白country节点到最近的非空父节点:

  • 定义键,把所有空白country的item节点,绑定到它前面最近的非空country节点的唯一ID上
  • 遍历所有非空country节点,通过键取出对应的子节点,统一生成表格层级

完整XSL代码

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

  <!-- 键:将空白country的item关联到最近的非空country父节点 -->
  <xsl:key name="child-items" match="item[@country='']" 
           use="generate-id(preceding-sibling::item[@country!=''][1])"/>

  <xsl:template match="/root">
    <html>
      <body>
        <table border="1">
          <!-- 遍历所有非空country的父节点 -->
          <xsl:for-each select="item[@country!='']">
            <!-- 父节点的country名称,跨列显示 -->
            <tr>
              <td colspan="2"><strong><xsl:value-of select="@country"/></strong></td>
            </tr>
            <!-- 输出父节点自身内容 -->
            <tr>
              <td> - </td>
              <td><xsl:value-of select="name"/></td>
            </tr>
            <!-- 取出关联的空白country子节点 -->
            <xsl:for-each select="key('child-items', generate-id(.))">
              <tr>
                <td> -- </td>
                <td><xsl:value-of select="name"/></td>
              </tr>
            </xsl:for-each>
          </xsl:for-each>
        </table>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>

关键代码说明

  • <xsl:key>:match定位所有空白country的节点,use通过preceding-sibling::item[@country!=''][1]找到最近的非空父节点,用generate-id生成唯一标识作为键值,确保空白节点能准确关联到所属父节点。
  • 内层循环用key('child-items', generate-id(.))直接取出当前父节点对应的所有空白子节点,替代原来有问题的循环逻辑,避免遍历所有节点导致的错误。

输出效果

生成的HTML表格会按国家分组,层级清晰:

层级内容
China
-Beijing
--Shanghai
--Guangzhou
USA
-New York
--Los Angeles

内容的提问来源于stack exchange,提问作者t2lhe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 20:20:14