如何使用PowerShell向XML新增标签中添加子元素
问题解决:PowerShell中为XML新增标签添加子元素
错误原因
报错是因为$xmlObject.configuration.authorization返回的是字符串类型,而非XML元素对象。当XML元素没有子元素且InnerText为空时,PowerShell会自动将其解析为字符串,自然没有AppendChild方法。
解决方案
创建<authorization>标签时,直接保留该元素的引用,后续添加子元素时直接使用这个引用,不要通过XML节点属性的方式二次获取。
修正后的代码
$file = "filepath" [System.Xml.XmlDocument]$xmlObject = New-Object System.Xml.XmlDocument $xmlObject = [System.Xml.XmlDocument](Get-Content $file) # 创建<authorization>标签并保存元素引用 $authElement = $xmlObject.CreateElement('authorization') $xmlObject.configuration.AppendChild($authElement) # 直接用保存的引用添加<deny>子元素 $denyElement = $xmlObject.CreateElement('deny') $denyElement.SetAttribute('users', '?') $authElement.AppendChild($denyElement) # 保存修改后的XML到文件 $xmlObject.Save($file)
关键说明
- 用
$authElement变量留存<authorization>的元素对象,后续直接调用其AppendChild方法,规避PowerShell自动解析为字符串的问题。 - 移除了不必要的
$newXmlElement.InnerText = "",创建空元素无需手动设置InnerText。 - 最后通过
$xmlObject.Save($file)确保修改写入目标文件。
内容的提问来源于stack exchange,提问作者QuadFacedDog
相关产品推荐
相关产品推荐

