且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 PowerShell 中为 XML 添加子元素

更新时间:2023-11-24 18:49:58

如果您使用点表示法来导航 XML 文件(例如 $doc.configuration),Powershell 会尝试巧妙地了解它的内容返回.

If you use dot notation to navigate an XML file (e.g. $doc.configuration), Powershell tries to be clever about what it returns.

  • 如果目标元素为空或只包含一个文本节点,PS 将返回一个String.
  • 如果目标元素包含文本节点以外的子节点,它将返回一个XmlElement.
  • 如果存在多个目标元素,它将返回一个 Object[],其中每个单独的数组元素再次受这些规则的约束,例如取决于其内容,它将是 StringXmlElement.
  • 如果目标元素不存在,PS返回$null.
  • 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 a String or an XmlElement depending on its contents.
  • If the target element does not exist, PS returns $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)

但您可以使用 $doc.SelectNodes()$doc.SelectSingleNode() 来浏览 XML 文档并始终返回一个节点/节点列表.

but you could use $doc.SelectNodes() or $doc.SelectSingleNode() to navigate around the XML document and always have a node/node list returned.

人们可能会争论这种行为的敏感性,但事实上,它使使用(结构合理的)XML 变得非常简单——例如,从配置文件或 API 响应中读取值等任务.这就是这个简单语法的目的.

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 的好工具,这是一项更复杂的任务.从一开始就使用 DOM API 方法是这里更好的方法.

It's not a good tool for creating XML, which is a more complex task. Using DOM API methods from the start is the better approach here.