如何在 PowerShell 中为 XML 添加子元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19245359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a child element for XML in PowerShell
提问by Warlock
I'm trying to create a child XML element for this xml:
我正在尝试为此 xml 创建一个子 XML 元素:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
</configuration>
I use this PowerShell script:
我使用这个 PowerShell 脚本:
[xml] $doc = Get-Content($filePath)
$child = $doc.CreateElement("newElement")
$doc.configuration.AppendChild($child)
I have an error: Method invocation failed because [System.String] doesn't contain a method named 'AppendChild'.
我有一个错误: 方法调用失败,因为 [System.String] 不包含名为“AppendChild”的方法。
回答by Tomalak
If you use dot notation to navigate an XML file (e.g. $doc.configuration), Powershell tries to be clever about what it returns.
如果您使用点表示法来导航 XML 文件(例如$doc.configuration),Powershell 会尽量巧妙地处理它返回的内容。
- If the target element is empty or only contains a single text node, PS will return a
String. - If the target element contains child nodes other than text nodes, it will return an
XmlElement. - If multiple target elements exist, it will return an
Object[], where each individual array element is again subject to these rules, e.g. it will either be aStringor anXmlElementdepending on its contents. - If the target element does not exist, PS returns
$null.
- 如果目标元素为空或仅包含单个文本节点,PS 将返回一个
String. - 如果目标元素包含文本节点以外的子节点,它将返回一个
XmlElement. - 如果存在多个目标元素,它将返回 an
Object[],其中每个单独的数组元素再次受这些规则的约束,例如,根据其内容,它将是 aString或 anXmlElement。 - 如果目标元素不存在,则 PS 返回
$null。
In your case it's easy since you want to append nodes to the document element:
在您的情况下,这很容易,因为您想将节点附加到文档元素:
$doc = New-Object System.Xml.XmlDocument
$doc.Load($filePath)
$child = $doc.CreateElement("newElement")
$doc.DocumentElement.AppendChild($child)
but you could use $doc.SelectNodes()or $doc.SelectSingleNode()to navigate around the XML document and always have a node/node list returned.
但是您可以使用$doc.SelectNodes()或$doc.SelectSingleNode()来浏览 XML 文档并始终返回一个节点/节点列表。
One could argue about the sensibility of this behavior, but as a matter of fact it makes consuming (sanely structured) XML quite straight-forward - for example tasks such as reading values from a config file, or from an API response. That's the purpose of this simple syntax.
人们可能会争论这种行为的敏感性,但事实上,它使使用(结构合理的)XML 变得非常简单——例如,从配置文件或 API 响应中读取值之类的任务。这就是这个简单语法的目的。
It's not a good tool for creatingXML, which is a more complex task. Using DOM API methods from the start is the better approach here.
它不是创建XML的好工具,这是一项更复杂的任务。从一开始就使用 DOM API 方法是这里更好的方法。

