Notepad++ - 如果与父节点的同级子节点匹配,则将 XML 节点替换为 XML 节点

Notepad++ - Replace XML node with XML node if matched with parent's sibling children nodes

提问人:thebernardlim 提问时间:11/15/2023 更新时间:11/15/2023 访问量:41

问:

我正在尝试替换XML节点类型的所有值,如果它与其父节点的同级子节点中的值匹配(不确定此处使用的正确术语)

下面是一个插图。

在下面的示例中,我想替换为 if 当前值匹配<productbrand><brandname><productbrand><id><brand>

以前:

<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>

目标:

<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>
记事本++

评论

0赞 Toto 11/15/2023
不要使用正则表达式修改XML文件,使用解析器更安全,更快捷且易于维护。stackoverflow.com/a/1732454/372239

答:

0赞 logi-kal 11/15/2023 #1

查找内容:

(<id>([^<>]*)</id>\s*<brandname>([^<>]*)</brandname>[\w\W]*<productbrand>)\2(?=</productbrand>)

替换为:

\1\3

单击“正则表达式”,然后单击“替换”,根据需要多次单击。

展开正则表达式:

(                    <- opening the first capturing group
  <id>               <- literally <id>
    (                <- opening second capturing group
      [^<>]*         <- zero or more times everything but < or >
    )                <- closing second capturing group
  </id>              <- literally </id>
  \s*                <- zero or more whitespaces
  <brandname>        <- literally <brandname>
    ([^<>]*)         <- third capturing group (as before)
  </brandname>       <- literally </brandname>
  [\w\W]*            <- zero or more times any possible character
  <productbrand>     <- literally <productbrand>
)                    <- closing the first capturing group
\2                   <- referencing the second capturing group
(?=</productbrand>)  <- followed by </productbrand>

截图:

Screenshot