I would like to find an easyer solution in inserting a string at the end of a tag (before the closing tag) in a xml file in windows.
This is a huge XML file with over 4000 lines.
At almost all lines there is an managedObject tag, and at the end i would like to insert a string: operation="create".
So it looks like this:

<managedObject class="blabla" ... id="1234">

..and want to make it like this:

<managedObject class="blabla" ... id="1234" operation="create">

As I said the XML file is huge, and not all lines have managedObject tags. I only want to insert the string were the managedObject tags are.

Up till now i did it manually..but it takes a lot of time..

1 Answers

0
LotPings On

I generally agree with @montonero that handling xml files with xml tools is the way to do it,
... but a quick hack for one time things with a RegEx can save time.

Here this PowerShell one liner using RegEx'es with lookarounds should do (presuming utf8 encoding):

(gc .\sample.xml -raw -enc utf8) -replace '(?<=\<managedobject)(?!.*?operation="create")([^\>]*?)\>','$1 operation="create">'|Set-Content new_sample.xml -enc utf8

Where

  • (?<=\<managedobject) is a zerolength lookbehind assertion matching the begin of the tag.
  • (?!.*?operation="create") is a zerolength negative lookahead assertion assuring not inserting operation="create" twice
  • ([^\>]*?) is a capture group to keep before the insertion.

Used on a sample file containing the above question yields:

I would like to find an easyer solution in inserting a string at the end of a tag (before the closing tag) in a xml file in windows.
This is a huge XML file with over 4000 lines.
At almost all lines there is an managedObject tag, and at the end i would like to insert a string: operation="create".
So it looks like this:

<managedObject class="blabla" ... id="1234" operation="create">

..and want to make it like this:

<managedObject class="blabla" ... id="1234" operation="create">

As I said the XML file is huge, and not all lines have managedObject tags. I only want to insert the string were the managedObject tags are.

Up till now i did it manually..but it takes a lot of time..