添加 XML 子元素 [英] adding XML sub-elements
问题描述
使用 PowerShell,我想将几个子元素添加到 XML 树中.
我知道添加一个元素,我知道添加一个或多个属性,但我不明白如何添加多个元素.
With PowerShell, I want to add several sub-elements into an XML tree.
I know to ADD ONE element, I know to add one or several attributes, but I don't understand how to ADD SEVERAL elements.
一种方法是将子 XML 树编写为文本
但是我不能使用这种方法,因为元素不是一次添加的.
One way whould be to write a sub-XML tree as text
But I can't use this method because the elements are not added at once.
要添加一个元素,我这样做:
To add one element, I do that:
[xml]$xml = get-content $nomfichier
$newEl = $xml.CreateElement('my_element')
[void]$xml.root.AppendChild($newEl)
工作正常.这给了我这个 XML 树:
Works fine. This give me this XML tree:
$xml | fc
class XmlDocument
{
root =
class XmlElement
{
datas =
class XmlElement
{
array1 =
[
value1
value2
value3
]
}
my_element = <-- the element I just added
}
}
现在我想向my_element"添加一个子元素.我使用类似的方法:
Now I want to add a sub element to 'my_element'. I use a similar method:
$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 树(部分显示):
This give this XML tree (partialy displayed):
my_element =
class XmlElement
{
my_sub_element =
another_one =
}
那些是属性,而不是子元素.
子元素将显示为:
Those are attributes, not sub-elements.
Sub-elements would be displayed as this:
my_element =
[
my_sub_element
another_one
]
问题:如何一次添加多个子元素?
Question: How do I add several sub-elements, one at a time?
推荐答案
看看下面的例子:
# 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")
<小时>
已编辑
这篇关于添加 XML 子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!