英文:
How to appen new elements into XML using powershell
问题
我需要在XML文件中创建新的标签,然后用新的元素填充该新标签。我将在一个脚本中多次执行此操作。我能够创建新的标签,但当我尝试用新元素填充它时出现错误。
$file = "文件路径"
[System.Xml.XmlDocument]$xmlObject = New-Object System.Xml.XmlDocument
$xmlObject = [System.Xml.XmlDocument](Get-Content $file)
#首先添加<authorization>标签
$newXmlElement = $xmlObject.CreateElement('authorization')
$newXmlElement.InnerText = ""
$xmlObject.configuration.AppendChild($newXmlElement)
#然后尝试用更多数据填充标签
$newXmlElement = $xmlObject.CreateElement('deny')
$newXmlElement.SetAttribute('users', '?')
$xmlObject.configuration.authorization.AppendChild($newXmlElement)
当我尝试在代码的最后一行调用新标签时,出现以下错误:
由于[System.String]不包含名为'AppendChild'的方法,因此方法调用失败。
我该如何填充新标签以及期望的结果:
<configuration>
<authorization>
<deny users="?" />
</authorization>
</configuration>
英文:
I need to create new tag within XML file and then fill the new tag with new elements. I will do this multiple times in one script. I am able to create the new tag but when i try to fill it with new elements i get an error.
My code so far:
$file = "filepath"
[System.Xml.XmlDocument]$xmlObject = New-Object System.Xml.XmlDocument
$xmlObject = [System.Xml.XmlDocument](Get-Content $file)
#first i add the <authorization> tag
$newXmlElement = $xmlObject.CreateElement('authorization')
$newXmlElement.InnerText = ""
$xmlObject.configuration.AppendChild($newXmlElement)
#then i try to fill the tag with more data
$newXmlElement = $xmlObject.CreateElement('deny')
$newXmlElement.SetAttribute('users', '?')
$xmlObject.configuration.authorization.AppendChild($newXmlElement)
When i try to call the new tag in last line of code i get this error:
Method invocation failed because [System.String] does not contain a method named 'AppendChild'
How would i go about filling the new tag with new element?
Desired result:
<configuration>
<authorization>
<deny users="?" />
</authorization>
</configuration>
答案1
得分: 1
我会在这种情况下使用xpath和“片段”:
$newelem=@'
<authorization>
<deny users="?" />
</authorization>
'@
$dest = $xmlObject.SelectSingleNode('//configuration')
$xmlFragment=$xmlObject.CreateDocumentFragment()
$xmlFragment.InnerXML=$newelem
$dest.AppendChild($xmlFragment)
英文:
I would use xpath and fragment
in this case:
$newelem=@'
<authorization>
<deny users="?" />
</authorization>
'@
$dest = $xmlObject.SelectSingleNode('//configuration')
$xmlFragment=$xmlObject.CreateDocumentFragment()
$xmlFragment.InnerXML=$newelem
$dest.AppendChild($xmlFragment)
This works for your simplified xml in the question and you may have to modify it to fit your actual xml file.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论