1

I have an xml file where I want to replace text in a parent node with some text from the child node. This is an example xml:

<output name="Element_152">
  <field name="NAME" key="true">Unit001</field>
  <field name="ITEM">CommStatus</field>
</output>
<output name="Element_153">
  <field name="NAME" key="true">Unit001</field>
  <field name="ITEM">UnitStatus</field>
</output>

I want to change the value of <output name="Element_..."> attribute to be the value from <field name="ITEM">, so I will get:

<output name="CommStatus">
  <field name="NAME" key="true">Unit001</field>
  <field name="ITEM">CommStatus</field>
</output>
<output name="UnitStatus">
  <field name="NAME" key="true">Unit001</field>
  <field name="ITEM">UnitStatus</field>
</output>

Thank you

1 Answer 1

0
  • Ctrl+H
  • Find what: (<output name=").+?(?=">(?:(?!</output>).)+<field name="ITEM">(.+?)</field>)
  • Replace with: $1$2
  • CHECK Match case
  • CHECK Wrap around
  • CHECK Regular expression
  • CHECK . matches newline
  • Replace all

Explanation:

(<output name=")            # literally, group 1
.+?                         # 1 or more any character, not greedy
(?=                         # positive lookahead, make sure we have after:
    ">                          # literally
    (?:                         # non capture group, Tempered Greedy Token
        (?!</output>)               # negative lookahead, make sure we haven't <:output> after
        .                           # any character
    )+                          # end group, must appear 1 or more times
    <field name="ITEM">         # literally
    (.+?)                       # group 2, 1 or more any character, not greedy
    </field>                    # literally
)                           # end lookahead

Replacement:

$1      # content of group 1 (<output name=")
$2      # content of group 2 (the value of ITEM)

Screenshot (before):

enter image description here

Screenshot (after):

enter image description here

2
  • Thanks!! This works great. Mar 15, 2021 at 12:49
  • @LironHallak: You're welcome, glad it helps.
    – Toto
    Mar 15, 2021 at 13:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .