1

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)

3
  • Please provide an exact error message, and describe how your code is not working. Commented Apr 24, 2017 at 15:27
  • Edited with the error Commented Apr 24, 2017 at 15:35
  • 2
    Xml-files can only have a single root-node Commented Apr 24, 2017 at 19:28

1 Answer 1

5

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>
Sign up to request clarification or add additional context in comments.

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.