October 6th, 2006

Adding elements to XML objects with Windows PowerShell

PowerShell Team
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.

Category
PowerShell

Author

PowerShell Team
PowerShell Team

PowerShell is a task-based command-line shell and scripting language built on .NET. PowerShell helps system administrators and power-users rapidly automate tasks that manage operating systems (Linux, macOS, and Windows) and processes.

0 comments

Discussion are closed.