Reputation: 21
I have this XML file:
<shows>
<breaking.bad />
<stranger.things />
</shows>
And i want to modify it using powershell so it will become:
<shows>
<breaking.bad />
<stranger.things />
</shows>
<movies>
</movies>
I tried this and it did not work:
$doc = [xml](get-content "c:\list.xml")
$movies = $doc.createelement("movies")
$doc.appendchild($movies)
There's an error saying: Exception calling "AppendChild" with "1" argument (s): "This document already has a 'DocumentElement' node." At line:3 char:1 + $doc.appendchild($movies)
Upvotes: 1
Views: 3109
Reputation: 13537
If you want to add another top level element, you need to add it to the container itself.
In order to make this work, I added a top level Document
node, and then made Shows
a child of that, like so.
[xml]$x = "
<document>
<shows>
<breaking.bad />
<stranger.things />
</shows>
</document>"
Then, I defined a new element just like you, by using the CreateElement
method. Finally, I added it to the Document.
$newElement = $x.CreateElement("movies")
$x.document.AppendChild($newElement)
And the output:
$x.OuterXml
<document><shows><breaking.bad /><stranger.things /></shows><movies /></document>
Upvotes: 5