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

如何用XSLT 2.0移除XML中双方括号[[...]]包裹的字符串

移除XML中[[...]]包裹内容的XSLT实现方案

原始输入XML

<root>
    <a>This is first para [[the first para1]]</a>
    <a>This is second para [[the second para2]]</a>
</root>

尝试的XSLT 2.0代码

<xsl:template match='@* | node()'>
    <xsl:copy>
        <xsl:apply-templates select='@* | node()'/>
    </xsl:copy>        
</xsl:template>
<xsl:template match="*[contains(text(),'[[')]"></xsl:template>

期望输出结果

<root>
   <a> This is first para</a>
   <a> This is second para</a>
</root>

问题分析与解决方案

你之前的代码错误匹配了包含[[的整个元素,用空模板直接删掉了整个<a>节点,不符合需求。正确做法是处理文本节点而非元素节点,通过正则替换移除指定格式内容。

以下是符合要求的XSLT 2.0代码:

<xsl:template match='@* | node()'>
    <xsl:copy>
        <xsl:apply-templates select='@* | node()'/>
    </xsl:copy>        
</xsl:template>

<xsl:template match="text()[contains(., '[[')]">
    <xsl:value-of select="replace(., '\[\[.*?\]\]', '')"/>
</xsl:template>

代码说明

  1. 第一个模板是身份模板,负责原样复制所有节点和属性,保证XML整体结构不变。
  2. 第二个模板专门匹配包含[[的文本节点,使用replace函数结合正则表达式:
    • \[\[匹配开头的[[(XML中转义后写为\[\[)
    • .*?是非贪婪匹配,确保只匹配到最近的]],避免多个包裹块时匹配范围错误
    • \]\]匹配结尾的]]
    • 最后用空字符串替换匹配到的内容,保留文本中需要的部分

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 22:33:25