添加XML子元素

前端之家收集整理的这篇文章主要介绍了添加XML子元素前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用PowerShell,我想将多个子元素添加到XML树中。
我知道添加一个元素,我知道添加一个或几个属性,但我不明白如何添加几个元素。

一种方式可能是write a sub-XML tree as text
但是我不能使用这种方法,因为元素不是立即添加的。

添加一个元素,我这样做:

  1. [xml]$xml = get-content $nomfichier
  2. $newEl = $xml.CreateElement('my_element')
  3. [void]$xml.root.AppendChild($newEl)

工作正常。这给我这个XML树:

  1. $xml | fc
  2. class XmlDocument
  3. {
  4. root =
  5. class XmlElement
  6. {
  7. datas =
  8. class XmlElement
  9. {
  10. array1 =
  11. [
  12. value1
  13. value2
  14. value3
  15. ]
  16. }
  17. my_element = <-- the element I just added
  18. }
  19. }

现在我要添加一个子元素到’my_element’。我使用类似的方法

  1. $anotherEl = $xml.CreateElement('my_sub_element')
  2. [void]$xml.root.my_element.AppendChild($anotherEl) <-- error because $xml.root.my_element is a string
  3. [void]$newEl.AppendChild($anotherEl) <-- ok
  4. $again = $xml.CreateElement('another_one')
  5. [void]$newEl.AppendChild($again)

这给这个XML树(部分显示):

  1. my_element =
  2. class XmlElement
  3. {
  4. my_sub_element =
  5. another_one =
  6. }

那些是属性,而不是子元素。
子元素将显示为:

  1. my_element =
  2. [
  3. my_sub_element
  4. another_one
  5. ]

问题:如何添加几个子元素,一次一个?

看看下面的例子:
  1. # Document creation
  2. [xml]$xmlDoc = New-Object system.Xml.XmlDocument
  3. $xmlDoc.LoadXml("<?xml version=`"1.0`" encoding=`"utf-8`"?><Racine></Racine>")
  4.  
  5. # Creation of a node and its text
  6. $xmlElt = $xmlDoc.CreateElement("Machine")
  7. $xmlText = $xmlDoc.CreateTextNode("Mach1")
  8. $xmlElt.AppendChild($xmlText)
  9.  
  10. # Creation of a sub node
  11. $xmlSubElt = $xmlDoc.CreateElement("Adapters")
  12. $xmlSubText = $xmlDoc.CreateTextNode("Network")
  13. $xmlSubElt.AppendChild($xmlSubText)
  14. $xmlElt.AppendChild($xmlSubElt)
  15.  
  16. # Creation of an attribute in the principal node
  17. $xmlAtt = $xmlDoc.CreateAttribute("IP")
  18. $xmlAtt.Value = "128.200.1.1"
  19. $xmlElt.Attributes.Append($xmlAtt)
  20.  
  21. # Add the node to the document
  22. $xmlDoc.LastChild.AppendChild($xmlElt);
  23.  
  24. # Store to a file
  25. $xmlDoc.Save("c:\Temp\Temp\Fic.xml")

编辑

备注:Using a relative path in Save will not do what you expect

猜你在找的XML相关文章