[英]Replacing XML nodes in PowerShell
I have two XML files (File1.xml, File2.xml). 我有两个XML文件(File1.xml,File2.xml)。 File2.xml is a subset of File1.xml.
File2.xml是File1.xml的子集。
File1.xml has nodes like so: File1.xml有这样的节点:
<parentnode>
<item id="GUID1">
<Text>Some Text</Text>
</item>
<item id="GUID2">
<Text>Here’s some more text</Text>
</item>
</parentnode>
File2.xml has: File2.xml有:
<parentnode>
<item id="GUID1">
<Text>Some Replacement Text</Text>
</item>
</parentnode>
I want to take the item with GUIDx in File1.xml, and replace it with the item with GUIDx from File2.xml. 我想借此与GUIDx在File1.xml的项目 ,与GUIDx从File2.xml的项目替换它。 Essentially, I want to take the replacement text in File2.xml and insert it into the corresponding item node in File1.xml
本质上,我想在File2.xml中获取替换文本并将其插入File1.xml中的相应项目节点
How do I do this in PowerShell? 我如何在PowerShell中执行此操作?
Suppose I have first xml in variable $edited
and the second in $new
. 假设我在变量
$edited
有第一个xml,在$new
有第二个。 Then you can change value in item with id GUID1 via 然后,您可以通过ID更改ID为GUID1的项目中的值
$edited.parentnode.item |
? { $_.id -eq 'guid1' } |
% { $_.Text = $new.parentnode.item.Text }
# and save the file
$edited.Save('d:\File1.xml')
# see the changes
gc d:\File1.xml
In case you have more items to replace, you could use nested pipelines: 如果您有更多要替换的项目,可以使用嵌套管道:
$edited = [xml]@"
<parentnode>
<item id="GUID1"><Text>Some Text</Text></item>
<item id="GUID2"><Text>Here’s some more text</Text></item>
<item id="GUID3"><Text>Here’s some more text</Text></item>
<item id="GUID10"><Text>Here’s some more text</Text></item>
</parentnode>
"@
$new = [xml] @"
<parentnode>
<item id="GUID1"><Text>new Guid1</Text></item>
<item id="GUID2"><Text>new Guid2</Text></item>
<item id="GUID3"><Text>new Guid3</Text></item>
<item id="GUID4"><Text>new Guid4</Text></item>
<item id="GUID5"><Text>new Guid5</Text></item>
</parentnode>
"@
$new.parentnode.item |
% { ,($_.id,$_.Text)} |
% { $id,$text = $_;
$edited.parentnode.item |
? { $_.id -eq $id } |
% { $_.Text = $text }
}
or foreach
cycle which is more readable here: 或
foreach
循环,这里更具可读性:
foreach($i in $new.parentnode.item) {
$edited.parentnode.item |
? { $_.id -eq $i.Id } |
% { $_.Text = $i.Text }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.