如何在 PowerShell 中为 XML 添加子元素 [英] How to add a child element for XML in PowerShell

查看:82
本文介绍了如何在 PowerShell 中为 XML 添加子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为此 xml 创建一个子 XML 元素:

I'm trying to create a child XML element for this xml:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
</configuration>

我使用这个 PowerShell 脚本:

I use this PowerShell script:

[xml] $doc = Get-Content($filePath)
$child = $doc.CreateElement("newElement")
$doc.configuration.AppendChild($child)

我有一个错误:方法调用失败,因为 [System.String] 不包含名为的方法'AppendChild'.

推荐答案

如果您使用点表示法来导航 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.

这篇关于如何在 PowerShell 中为 XML 添加子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆