简体   繁体   中英

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. 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?

For example I have a file called serial.txt with the following values:

 123456
 123566  

And I have an xml file called data.xml with the following content:

<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?

$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

$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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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