Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change text in a XML element?

Tags:

powershell

xml

Let's say I have the following XML element:

<test> 1000 </test>

I want to change it to:

<test > 500 </test>

Using PowerShell how would I do this.

I know how to make the xml object with PowerShell and make a node variable to access a certain node within the XML. I just don't know the exact command(s) to replace the text inside the node.

like image 871
Rameen Rastan Avatar asked Aug 26 '15 14:08

Rameen Rastan


2 Answers

As with everything PowerShell this can be done multiple ways. If you had an element such as <test name="frank">Some Text</test> you could change it by doing:

[xml]$xml = '<test name="frank">Some Text</test>'
$xml.test.InnerText = "Some Other Text"

If, however, your element is simple as described in the question (<test>1000</test>) you need to be a little careful.

[xml]$xml = "<test>1000</test>"
$elements = $xml.SelectSingleNode("//test")
$elements[0].'#text' = "500"

The reason for this is that PowerShell will return a string for $xml.test and setting this string doesn't update the XmlDocument.

like image 109
Mr Tree Avatar answered Sep 30 '22 21:09

Mr Tree


If you have a certain node you can set node.InnerText = 500.

like image 24
Martin Honnen Avatar answered Sep 30 '22 22:09

Martin Honnen