xml - Powershell 替换 XML 文件中的值

标签 xml powershell

我有 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/

相关文章:

powershell - 使用PoSH取值,奇怪的结果

powershell - PowerShell:如何处理csv.file中的当前对象?

powershell - 通过 SSL 证书和 powershell 创建 https 绑定(bind)时的 "IIS: Cannot create a file when that file already exists.Exception.Message"

java - 没有时区信息的 XmlBeans XmlDateTime 格式

powershell - 具有十六进制值的 Invoke-WebRequest

c# - 在 C# 中有选择地抑制 XML 代码注释?

Java - 使程序从文件加载选项的最佳方法是什么?

powershell - TeamCity、存储库中文件的版本号和程序集修补程序

javascript - 如何在 Express.js 中将 JS 字符串作为 xml 文档发送给用户?

php - 将输入从 "GET"发送到 php 中的 xml 文件