我正在尝试更改XML的特定元素。我有以下XML文件:
<?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>
我想改变:
<file name="FileName.mp4" hashCode="123456789" />
到
<file name="FileName.mp4" hashCode="ChangingTest" />
我想出了以下脚本来访问这个元素,但我似乎无法弄清楚要更改它的人。
这是我目前正在使用的powershell脚本:
[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')
我不确定我在这里缺少什么,但我会很感激我可能错过的任何方向/资源。
答案 0 :(得分:2)
您需要在实际数组上指定索引才能修改属性。你有一组file
- 对象。尝试:
$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"
当您编写.hashcode
时,您实际上正在使用成员枚举,这是为hashcode
- 数组中的每个元素提取file
- 值的快捷方式。这样做时,这些值将是只读的。