加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

添加XML子元素

发布时间:2020-12-16 08:02:36 所属栏目:百科 来源:网络整理
导读:使用PowerShell,我想将多个子元素添加到XML树中。 我知道添加一个元素,我知道添加一个或几个属性,但我不明白如何添加几个元素。 一种方式可能是write a sub-XML tree as text 但是我不能使用这种方法,因为元素不是立即添加的。 要添加一个元素,我这样做
使用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:TempTempFic.xml")

编辑

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读