更新时间: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.
String
.XmlElement
.Object[]
,其中每个单独的数组元素再次受这些规则的约束,例如取决于其内容,它将是 String
或 XmlElement
.$null
.String
.XmlElement
.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.$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.