Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set x XML node to value in Powershell

I have this PowerShell script in which values for an XML-file will be set by the script. This works perfectly fine when all child nodes are uniquely named. However, I'm adapting the XML-file to one where some nodes are repeated. Now I get an error in Powershell.

My question is, how to set the X'th node in XML to a certain value via PowerShell?

In short, my script works like the following:

cls

[xml] $xml1 = '<Lvl1>
                    <Lvl2>""</Lvl2>
                    <Lvl2>""</Lvl2>
                </Lvl1>' 

$xml1.Lvl1.Lvl2='./'

$xml1.Save("text.xml")

There is two times the same node (Lvl2), that's why I get the following error in PowerShell: "Cannot set "Lvl2" because only strings can be used as values to set XmlNode properties."

When I remove one (Lvl2) node, the script works like a charm.

Please advice.

like image 366
Sunfile Avatar asked Oct 21 '25 05:10

Sunfile


1 Answers

You can always use .NET syntax, it works like a charm.

$xml1.SelectSingleNode('Lvl1/Lvl2[2]').InnerText='./'
like image 69
Paweł Dyl Avatar answered Oct 23 '25 21:10

Paweł Dyl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!