7

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.

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I'd prefer SelectSingleNode('//test') over GetElementsByTagName('test').
Of course. There are multiple ways to select the element, but the key is to not use $xml.test if the element has only text as powershell will parse this as a string and appears to not update the XMLElement when the string is modified. I'll update my answer to clarify this.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.