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

如何在XSLT中用not排除节点子元素并生成两个response节点?

用单份XSLT实现两种节点保留逻辑的方案

当然可以用同一份XSLT搞定这个需求!核心思路是利用XSLT的**模式(mode)**区分两种处理逻辑,再结合你提到的not()语法来精准排除不需要的节点。下面是具体的实现方案:

核心思路拆解

  • 匹配原始response根节点,触发两次不同的处理流程
  • 第一次处理:保留Applicants和Assets,用not()排除Liabilities
  • 第二次处理:保留Applicants和Liabilities,用not()排除Assets
  • 模式(mode)是实现同一XSLT输出两种结果的关键,它允许我们对同一节点应用不同的规则

完整XSLT代码

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <!-- 匹配根节点,触发两次不同模式的处理 -->
    <xsl:template match="/response">
        <!-- 生成第一个response:保留Applicants + Assets -->
        <xsl:apply-templates select="." mode="keep-assets"/>
        <!-- 生成第二个response:保留Applicants + Liabilities -->
        <xsl:apply-templates select="." mode="keep-liabilities"/>
    </xsl:template>

    <!-- 模式1:用not()排除Liabilities,保留Applicants和Assets -->
    <xsl:template match="response" mode="keep-assets">
        <response context="{@context}" type="{@type}" errorCode="{@errorCode}">
            <output>
                <!-- 选择output下所有子节点,除了Liabilities -->
                <xsl:copy-of select="output/*[not(local-name()='Liabilities')]"/>
            </output>
        </response>
    </xsl:template>

    <!-- 模式2:用not()排除Assets,保留Applicants和Liabilities -->
    <xsl:template match="response" mode="keep-liabilities">
        <response context="{@context}" type="{@type}" errorCode="{@errorCode}">
            <output>
                <!-- 选择output下所有子节点,除了Assets -->
                <xsl:copy-of select="output/*[not(local-name()='Assets')]"/>
            </output>
        </response>
    </xsl:template>

    <!-- 通用模板:确保节点和属性的默认复制逻辑 -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

代码说明

  • 如果你觉得直接选择需要的节点更直观,也可以把copy-of语句改成<xsl:copy-of select="output/Applicants | output/Assets"/>,和用not()的效果完全一致
  • 模板里的属性值通过{@属性名}的方式直接复用原始XML的属性,保证输出和输入的上下文信息一致

输出效果验证

把你提供的XML输入到这份XSLT中,会生成两个独立的response节点:
第一个节点(保留Applicants和Assets):

<response context="XXXX" type="abcd" errorCode="0">
   <output>
      <Applicants>
         <Applicant>
            <IndividualEmployments/>
            <Addresses/>
         </Applicant>
      </Applicants>
      <Assets>
         <Asset id="12345"/>
      </Assets>
   </output>
</response>

第二个节点(保留Applicants和Liabilities):

<response context="XXXX" type="abcd" errorCode="0">
   <output>
      <Applicants>
         <Applicant>
            <IndividualEmployments/>
            <Addresses/>
         </Applicant>
      </Applicants>
      <Liabilities>
         <Liability id="8765"/>
      </Liabilities>
   </output>
</response>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 12:07:37