【问题标题】:Powershell inserting multiple XML elementsPowershell插入多个XML元素
【发布时间】:2012-05-10 07:30:41
【问题描述】:

我有一个类似于以下结构的 XML 文件:

<a>
  <b>
    <c>aa</c>
  </b>
  <d>
    <e>bb</e>
  </d>
</a>

我需要做的是在 中插入额外的元素,以获得以下内容:

<a>
  <b>
    <c>aa</c>
  </b>
  <d>
    <e>bb</e>
    <e>cc</e>
    <e>dd</e>
    <e>ff</e>
    <e>gg</e>
  </d>
</a>

我正在尝试在 Powershell 中执行此操作。这是我尝试过的:

$xml = "path_to_xml_file"
$e1 = $xml.a.d.e
$e2 = $e1.clone()
$e2 = "cc"
$xml.a.d.InsertAfter($e2,$e1)
$xml.save("path_to_xml_file")

但这给了我一个错误。有人可以建议如何去做吗?

【问题讨论】:

    标签: powershell


    【解决方案1】:

    您应该在XmlDocument 实例上使用CreateElement 方法,例如:

    $xml = [xml]@'
    <a>
      <b>
        <c>aa</c>
      </b>
      <d>
        <e>bb</e>
      </d>
    </a>
    '@
    
    $newNode = $xml.CreateElement('e')
    $newNode.InnerText = "cc"
    $xml.a.d.AppendChild($newNode) 
    

    此外,如果从文件中获取 XML,您应该使用:

    $xml = [xml](Get-Content path_to_xml_file)
    

    【讨论】:

    • 非常感谢!完美运行
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    相关资源
    最近更新 更多