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

如何在XSLT模板匹配的XPath中添加OR条件并筛选指定节点?

解决你的XSLT筛选需求

没问题,我来帮你搞定这个XSLT筛选需求!首先明确你的目标:保留<A1>节点中<B1>值为CAT的条目,以及<A2>节点中<B1>值为DOG的条目,排除其他不符合条件的节点(比如示例里的<A3>)。

输入XML示例

先确认你的输入结构:

<MAIN>
 <A1>
  <B1>CAT</B1>
  <B2>KITTEN</B2>
 </A1>
 <A2>
  <B1>DOG</B1>
  <B2>PUPPY</B2>
 </A2>
 <A3>
  <B1>LION</B1>
  <B2>CUB</B2>
 </A3>
</MAIN>

方案一:直接筛选复制(简洁高效)

这个方案通过xsl:copy-of直接选中符合条件的节点,代码简洁易懂,适合大多数场景:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    
    <!-- 匹配MAIN节点,保留其结构并筛选子节点 -->
    <xsl:template match="MAIN">
        <xsl:copy>
            <!-- 筛选B1值为CAT的A1节点 -->
            <xsl:copy-of select="A1[B1='CAT']"/>
            <!-- 筛选B1值为DOG的A2节点 -->
            <xsl:copy-of select="A2[B1='DOG']"/>
        </xsl:copy>
    </xsl:template>
    
    <!-- 忽略多余的文本节点,避免输出空白 -->
    <xsl:template match="text()"/>
</xsl:stylesheet>

方案二:模板匹配(灵活扩展)

如果后续需要对不同节点做个性化处理,推荐用模板匹配的方式,扩展性更强:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    
    <!-- 处理根节点,触发模板匹配 -->
    <xsl:template match="/">
        <xsl:apply-templates/>
    </xsl:template>
    
    <!-- 保留MAIN节点结构 -->
    <xsl:template match="MAIN">
        <xsl:copy>
            <xsl:apply-templates/>
        </xsl:copy>
    </xsl:template>
    
    <!-- 匹配并保留符合条件的A1节点 -->
    <xsl:template match="A1[B1='CAT']">
        <xsl:copy-of select="."/>
    </xsl:template>
    
    <!-- 匹配并保留符合条件的A2节点 -->
    <xsl:template match="A2[B1='DOG']">
        <xsl:copy-of select="."/>
    </xsl:template>
    
    <!-- 忽略所有不符合条件的节点 -->
    <xsl:template match="*"/>
</xsl:stylesheet>

输出结果

两种方案都会得到如下符合需求的XML:

<MAIN>
  <A1>
    <B1>CAT</B1>
    <B2>KITTEN</B2>
  </A1>
  <A2>
    <B1>DOG</B1>
    <B2>PUPPY</B2>
  </A2>
</MAIN>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:42:04