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

XSLT 1.0需求:移除无有效addresses子节点的customer元素

解决XSLT 1.0移除无有效addresses的customer元素问题

输入XML

<response>
<customers>
    <customer>
        <id>001</id>
        <addresses>
            <address>
                <id>a01</id>
                <street/>
            </address>
            <address>
                <id>a02</id>
                <street/>
            </address>
        </addresses>
    </customer>
    <customer>
        <id>002</id>
        <addresses/>
    </customer>
</customers>
</response>

期望输出

<response>
<customers>
    <customer>
        <id>001</id>
        <addresses>
            <address>
                <id>a01</id>
                <street/>
            </address>
            <address>
                <id>a02</id>
                <street/>
            </address>
        </addresses>
    </customer>
</customers>
</response>

原XSLT代码问题

你使用的XSLT匹配条件逻辑偏差,无法正确识别需移除的customer节点:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="customer[not(descendant::address[not(*)][normalize-space()])]"/>
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>
</xsl:stylesheet>

修正后的XSLT代码

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

    <!-- 移除无addresses或addresses为空的customer节点 -->
    <xsl:template match="customer[not(addresses) or not(addresses/node())]"/>

    <!-- 身份模板:复制所有未被特殊匹配覆盖的节点 -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

代码说明

  • 核心匹配条件 customer[not(addresses) or not(addresses/node())]:
    • not(addresses):匹配不存在addresses子节点的customer
    • not(addresses/node()):匹配存在addresses子节点但该节点无任何内容(空标签)的customer
  • 身份模板负责保留所有未被移除逻辑命中的节点,保证XML原有结构正常复制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 05:45:42