Adding elements to XML objects with Windows PowerShell

PowerShell Team

While it’s very easy to load and view the content of XML documents how do you add new elements? Here’s how:

Let’s create a simple XML document, one parent node with two children:

PS> [xml]$x = “<top>

<first>first child</first>

<second>second child</second>

   </top>”

PS> $x.top

first                                   second
—–                                   ——
first child                             second child

Add a new element below our top element with textual content:

PS> $e = $x.CreateElement(“third”)
PS> $e.set_InnerText(“third child”)

(Windows PowerShell wraps .Net object properties with method calls. The method set_InnerText actually refers to the .Net property InnerText, and is required because our XML adapter assumes that all properties come from your XML)

PS> $x.top.AppendChild($e)

What does our XML look like now?

PS> $x.top

first                      second                     third
—–                      ——                     —–
first child                second child               third child

That’s it!

 

Nigel Sharples [MSFT]
Windows PowerShell Team
Microsoft Corporation
This posting is provided “AS IS” with no warranties, and confers no rights.

0 comments

Discussion is closed.

Feedback usabilla icon