2

I'm trying to change a specific element of an XML. I have the following XML File:

<?xml version="1.0" encoding="utf-8"?>
<recording-event>
  <video hashType="none">
    <streams>
      <stream num="1" start-tick="01234567890" stop-tick="02134567890">
        <file name="FileName.mp4" hashCode="123456789" />
        <file name="FileName.vtt" hashCode="987654312" />
        <file name="FileName.json" hashCode="10111213" />
      </stream>
    </streams>
  </video>
</recording-event>

I'm trying to change:

<file name="FileName.mp4" hashCode="123456789" />

to

<file name="FileName.mp4" hashCode="ChangingTest" />

I've come up with the following script to access this element, but I can't seem to figure out who to change it.

Here is the powershell script i'm currently using:

[xml]$content = Get-Content "C:\Users\WG\Desktop\test.xml"

$content.'recording-event'.video.streams.stream.file.hashCode.Item(0)
$content.'recording-event'.video.streams.stream.file.hashCode.Item(0) = 'ChangingTest'
$content.'recording-event'.video.streams.stream.file.hashCode.Item(0)

$content.Save('C:\Users\WG\Desktop\test.xml')

I'm not sure what I'm missing here, but would appreciate any direction/resources I may have missed on this.

sms5138
  • 47
  • 3

1 Answers1

2

You need to specify the index on the actual array to be able to modify the properties. You have an array of file-objects. Try:

$content.'recording-event'.video.streams.stream.file.Item(0).hashCode = 'ChangingTest'

#Or the PowerShell-way to use index
$content.'recording-event'.video.streams.stream.file[0].hashcode = "test3"

#Or xpath to get the mp4-node (if the order has suddenly changed)
$content.'recording-event'.video.streams.stream.SelectSingleNode("file[contains(@name,'.mp4')]").hashcode = "hash4"

When you write .hashcode you are actually using member enumeration which is a shortcut to extract the hashcode-value for each element in the file-array. The values will be read-only when doing this.

Frode F.
  • 52,376
  • 9
  • 98
  • 114