如何在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
相关产品推荐
相关产品推荐

