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

Notepad++中基于父节点同级子节点匹配替换XML节点值

在Notepad++中实现XML节点的匹配替换

需求说明:
将XML中<productbrand>节点的内容,替换为与该节点值匹配的<brands>模块下对应<brand>节点的<brandname>值(匹配依据是<productbrand>的值等于<brand>下<id>的值)。

示例

替换前(Before)

<catalog>
<brands>
    <brand>
        <id>123</id>
        <brandname>Brand A</brandname>
    </brand>
    <brand>
        <id>456</id>
        <brandname>Brand B</brandname>
    </brand>
<brands>
<products>
    <product>
        <name>A</name>
        <productbrand>123</productbrand>
    </product>
    <product>
        <name>B</name>
        <productbrand>456</productbrand>
    </product>
</products>
</catalog>

替换后(Goal)

<catalog>
    <brands>
        <brand>
            <id>123</id>
            <brandname>Brand A</brandname>
        </brand>
        <brand>
            <id>456</id>
            <brandname>Brand B</brandname>
        </brand>
    <brands>
    <products>
        <product>
            <name>A</name>
            <productbrand>Brand A</productbrand>
        </product>
        <product>
            <name>B</name>
            <productbrand>Brand B</productbrand>
        </product>
    </products>
    </catalog>

操作步骤

方案一:Python脚本插件(推荐,适合批量处理)

Notepad++内置正则无法直接跨模块建立映射批量替换,需借助Python Script插件实现:

  1. 打开目标XML文件,通过「插件管理器」搜索安装Python Script插件。
  2. 点击菜单栏「Plugins」→「Python Script」→「New Script」,新建脚本文件(比如命名为ReplaceProductBrand.py)。
  3. 将以下代码粘贴到脚本中:
import re

# 获取当前文档内容
content = editor.getText()

# 提取所有品牌的ID与名称映射
brand_map = {}
brand_pattern = re.compile(r'<brand>\s*<id>(\d+)</id>\s*<brandname>([^<]+)</brandname>\s*</brand>', re.DOTALL)
matches = brand_pattern.findall(content)
for brand_id, brand_name in matches:
    brand_map[brand_id] = brand_name

# 替换productbrand节点内容
def replace_match(match):
    target_id = match.group(1)
    return f'<productbrand>{brand_map.get(target_id, target_id)}</productbrand>'

product_pattern = re.compile(r'<productbrand>(\d+)</productbrand>')
new_content = product_pattern.sub(replace_match, content)

# 写入替换后的内容
editor.setText(new_content)
  1. 保存脚本后,点击「Plugins」→「Python Script」→「Scripts」→「ReplaceProductBrand」运行,完成替换。

方案二:纯正则分步替换(适合品牌数量少的场景)

无需插件,针对每个品牌单独替换:

  1. 打开替换窗口(快捷键Ctrl+H),勾选「正则表达式」,取消「. matches newline」选项。
  2. 查找内容填:<productbrand>123</productbrand>,替换为:<productbrand>Brand A</productbrand>,点击「全部替换」。
  3. 重复上述步骤,依次替换其他品牌的对应内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 13:43:21