如何在PowerShell中向现有XML数据添加元素
问题:向现有XML文件添加Items元素时触发DocumentElement错误
现有XML结构
<Certs> <Items> <Guid>Value1</Guid> <Name>Value2</Name> </Items> <Items> <Guid>Value3</Guid> <Name>Value4</Name> </Items> </Certs>
编写的PowerShell代码
$xmldata = New-Object System.Xml.XmlWriterSettings $xmldata.Indent = $true $xmldata = [xml](Get-Content -Path C:\lists\certificates.xml) $rootElement = $xmldata.CreateElement("Certs") $xmldata.AppendChild($rootElement) $childElement1 = $xmldata.CreateElement("Items") $rootElement.AppendChild($childElement1) $xmldata.AppendChild($childElement1)
报错信息
Exception calling "AppendChild" with "1" argument(s): "This document already has a 'DocumentElement' node."
At C:\lists\communication.ps1:9 char:1
- $xmldata.AppendChild($rootElement)
- CategoryInfo : NotSpecified: (:) [], MethodInvocationException
- FullyQualifiedErrorId : DotNetMethodException
问题原因与解决方法
错误核心是重复创建了根节点<Certs>——XML文档只能有一个根节点,你读取的文件已经存在<Certs>作为根节点,无需再创建。正确操作是直接获取已有根节点,向其添加新的<Items>元素。
修正后的代码示例
# 读取现有XML文件 $xmldata = [xml](Get-Content -Path C:\lists\certificates.xml) # 获取已存在的根节点Certs $rootElement = $xmldata.Certs # 创建新的Items元素 $newItems = $xmldata.CreateElement("Items") # 创建并添加Guid子元素 $guidElement = $xmldata.CreateElement("Guid") $guidElement.InnerText = "NewGuidValue" $newItems.AppendChild($guidElement) # 创建并添加Name子元素 $nameElement = $xmldata.CreateElement("Name") $nameElement.InnerText = "NewNameValue" $newItems.AppendChild($nameElement) # 将新的Items添加到根节点下 $rootElement.AppendChild($newItems) # 保存修改后的XML文件(可指定新路径避免覆盖原文件) $xmldata.Save("C:\lists\certificates.xml")
代码说明
- 直接通过
$xmldata.Certs获取已有根节点,无需重新创建 - 每个新
<Items>元素需包含对应的<Guid>和<Name>子元素,设置文本值后再添加到根节点 - 必须调用
Save()方法才能将修改写入文件 - 原代码中未使用的
XmlWriterSettings可直接删除
内容的提问来源于stack exchange,提问作者JensH
相关产品推荐
相关产品推荐

