简体   繁体   English

Powershell:将节点添加到XML根目录

[英]Powershell: Add node to XML root

I have this XML file: 我有这个XML文件:

<shows>
    <breaking.bad />
    <stranger.things />
</shows>

And i want to modify it using powershell so it will become: 我想使用powershell对其进行修改,因此它将变为:

<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." 有一个错误说:用“ 1”自变量调用“ AppendChild”的异常:“此文档已经有一个'DocumentElement'节点。” At line:3 char:1 + $doc.appendchild($movies) 在第3行:char:1 + $ doc.appendchild($ movies)

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. 为了完成这项工作,我添加了一个顶级Document节点,然后像这样使Shows成为子节点。

[xml]$x = "
<document>
   <shows>
    <breaking.bad />
    <stranger.things />
  </shows>
</document>"

Then, I defined a new element just like you, by using the CreateElement method. 然后,通过使用CreateElement方法,像您一样定义了一个新元素。 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM