我有 2 个 XML 文件,我正在从第一个文件中读取一个值,需要用特定字符串替换第二个 XML 中的该值,这是我到目前为止得到的,它不能很好地工作,它会改变整个文件由于某种原因 XML 到 #document
编辑 重新设计脚本的整个逻辑,我一直在修剪节点,在 IdexOf 处收到错误,为什么?
<BunnyTemplate> <Parm Name="A-1" Source="Application" OnAbsence="1.com"> <Parm Name="A-2" Source="Application" OnAbsence="2.com"> <Parm Name="A-3" Source="Application" OnAbsence="\\3\3"/> <Parm Name="A-4" Source="Application" OnAbsence="4.com"> </BunnyTemplate>
$file1 = "C:\..\Desktop\file1.xml"
$file1Content = [xml](Get-Content $file1)
$targetNode = $file1Content.SelectSingleNode("//General/@findMe")
$trimmedNode = $targetNode.Substring(0, $targetNode.IndexOf('last'))
最佳答案
不要使用-replace
在 XML 文档上,使用 XPath
相反。
假设$file2
包含:
<BunnyTemplate>
<Parm Name="Bunny" Source="Bunny" OnAbsence="value-to-replace"/>
</BunnyTemplate>
...您可以执行以下操作:
$file2Xml = [xml](Get-Content $file2)
# Locate target node
$targetNode = $file2Xml.SelectSingleNode("//Parm[@OnAbsence]")
# Overwrite attribute value
$targetNode.SetAttribute('OnAbsence', "text${trimmedNode}")
# save file
$file2Xml.Save("C:\path\to\output.xml")
SelectSingleNode("//Parm[@OnAbsence]")
将返回第一个<Parm>
具有 OnAbsence
的节点属性。
如果您特别需要使用Source="Bunny"
来定位一个,您可以使用//Parm[@Source = 'Bunny']
相反
关于xml - Powershell 替换 XML 文件中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61733229/