Home > Back-end >  Edit XML Nodes via Powershell
Edit XML Nodes via Powershell

Time:06-10

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  
}

CodePudding user response:

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")
  • Related