简体   繁体   English

通过 Powershell 编辑 XML 节点

[英]Edit XML Nodes via Powershell

I am trying to add a list of serial numbers to an XML file and use powershell to automate this.我正在尝试将序列号列表添加到 XML 文件并使用 powershell 自动执行此操作。 I am so far able to open the xml document and get the value of the "serialNo" value, but how would I loop through and modify this?到目前为止,我能够打开 xml 文档并获取“serialNo”值的值,但是我将如何循环并修改它呢?

For example I have a file called serial.txt with the following values:例如,我有一个名为 serial.txt 的文件,其中包含以下值:

 123456
 123566  

And I have an xml file called data.xml with the following content:我有一个名为 data.xml 的 xml 文件,其内容如下:

<form1>

<label1>
<label>
<serialNo> </serialNo>
<barcodeNo/>
</label>
</label1>
<label2>
<label>
<serialNo> </serialNo>
<barcodeNo/>
</label>
</label2>

</form1>

This is my powershell code so far, I am able to get the values from the xml file, but how do I loop through and modify the serialNo node?到目前为止,这是我的 powershell 代码,我能够从 xml 文件中获取值,但是如何循环并修改 serialNo 节点?

$serialNumbers = Get-Content ".\serial.txt"

[xml]$xmlDoc = Get-Content ".\data.xml"

$nodes = $xmlDoc.SelectNodes("//serialNo")


$i = 1;
foreach($node in $nodes){

     $node.'#text' = $serialNumbers[$i]
     $i++
}

This is the end script thanks to mclayton and Theo感谢 mclayton 和 Theo,这是结束脚本

$serialNumbers = Get-Content "C:\Users\user1\Desktop\PowerShellExperiment\test\serial.txt"

[xml]$xmlDoc = Get-Content "C:\Users\user1\Desktop\PowerShellExperiment\test\data.xml"

$nodes = $xmlDoc.SelectNodes("//serialNo")


$i = 0;
foreach($node in $nodes){

     $node.InnerText = $serialNumbers[$i]
     $i++
}

$xmlDoc.Save("C:\Users\user1\Desktop\PowerShellExperiment\test\data.xml")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM