使用PowerShell,我想将多个子元素添加到XML树中。
我知道添加一个元素,我知道添加一个或几个属性,但我不明白如何添加几个元素。
我知道添加一个元素,我知道添加一个或几个属性,但我不明白如何添加几个元素。
一种方式可能是write a sub-XML tree as text
但是我不能使用这种方法,因为元素不是立即添加的。
要添加一个元素,我这样做:
- [xml]$xml = get-content $nomfichier
- $newEl = $xml.CreateElement('my_element')
- [void]$xml.root.AppendChild($newEl)
工作正常。这给我这个XML树:
- $xml | fc
- class XmlDocument
- {
- root =
- class XmlElement
- {
- datas =
- class XmlElement
- {
- array1 =
- [
- value1
- value2
- value3
- ]
- }
- my_element = <-- the element I just added
- }
- }
现在我要添加一个子元素到’my_element’。我使用类似的方法:
- $anotherEl = $xml.CreateElement('my_sub_element')
- [void]$xml.root.my_element.AppendChild($anotherEl) <-- error because $xml.root.my_element is a string
- [void]$newEl.AppendChild($anotherEl) <-- ok
- $again = $xml.CreateElement('another_one')
- [void]$newEl.AppendChild($again)
这给这个XML树(部分显示):
- my_element =
- class XmlElement
- {
- my_sub_element =
- another_one =
- }
- my_element =
- [
- my_sub_element
- another_one
- ]
问题:如何添加几个子元素,一次一个?
看看下面的例子:
- # Document creation
- [xml]$xmlDoc = New-Object system.Xml.XmlDocument
- $xmlDoc.LoadXml("<?xml version=`"1.0`" encoding=`"utf-8`"?><Racine></Racine>")
- # Creation of a node and its text
- $xmlElt = $xmlDoc.CreateElement("Machine")
- $xmlText = $xmlDoc.CreateTextNode("Mach1")
- $xmlElt.AppendChild($xmlText)
- # Creation of a sub node
- $xmlSubElt = $xmlDoc.CreateElement("Adapters")
- $xmlSubText = $xmlDoc.CreateTextNode("Network")
- $xmlSubElt.AppendChild($xmlSubText)
- $xmlElt.AppendChild($xmlSubElt)
- # Creation of an attribute in the principal node
- $xmlAtt = $xmlDoc.CreateAttribute("IP")
- $xmlAtt.Value = "128.200.1.1"
- $xmlElt.Attributes.Append($xmlAtt)
- # Add the node to the document
- $xmlDoc.LastChild.AppendChild($xmlElt);
- # Store to a file
- $xmlDoc.Save("c:\Temp\Temp\Fic.xml")
编辑
备注:Using a relative path in Save will not do what you expect。