1

I have an xml file where each element formatted like this:

    <ScriptEvent xsi:type="Event">
      <_time>0</_time>
    </ScriptEvent>
    <ScriptEvent xsi:type="Event">
      <_time>1</_time>
    </ScriptEvent>
    <ScriptEvent xsi:type="Event">
      <_time>2</_time>
    </ScriptEvent>
    <ScriptEvent xsi:type="Event">
      <_time>3</_time>
    </ScriptEvent>

I'm wondering how I can change the xml like this:

  1. We will have a variable "count", and this is the value we will use to replace the current "_time" element
  2. Every two ScriptEvent elements, this count will increase by one.

So for example, the expected output file will look like this:

    <ScriptEvent xsi:type="Event">
      <_time>0</_time>
    </ScriptEvent>
    <ScriptEvent xsi:type="Event">
      <_time>0</_time>
    </ScriptEvent>
    <ScriptEvent xsi:type="Event">
      <_time>1</_time>
    </ScriptEvent>
    <ScriptEvent xsi:type="Event">
      <_time>1</_time>
    </ScriptEvent>

I'm not very good with powershell, can someone help me think of a working powershell script for this? The xml file I have actually have a lot of these ScriptEvent elements (over 400k of them).

Thank you very much.

DarkChocoBar
  • 77
  • 1
  • 12

1 Answers1

2

Here's a simplified example, which takes advantage of PowerShell's convenient adaptation of the XML DOM provided by the [xml] class (System.Xml.XmlDocument):

# Parse XML text into a DOM.
[xml] $xmlDoc = @'
<root xmlns:xsi="http://example.org" >    
    <ScriptEvent xsi:type="Event">
      <_time>0</_time>
    </ScriptEvent>
    <ScriptEvent xsi:type="Event">
      <_time>1</_time>
    </ScriptEvent>
    <ScriptEvent xsi:type="Event">
      <_time>2</_time>
    </ScriptEvent>
    <ScriptEvent xsi:type="Event">
      <_time>3</_time>
    </ScriptEvent>
</root>    
'@

# Loop over all <ScriptElement> children of the <root> element
# and update their <_time> values.
$i = 0; $count = 0
foreach ($el in $xml.root.ScriptEvent) {
  $el._time = $count
  if ($i++ % 2) { ++$count }
}

For information on how to load XML from a file and how to pretty-print on saving back to a file, see this answer.

mklement0
  • 382,024
  • 64
  • 607
  • 775