【问题标题】:XML add new child to each element child of array nodeXML向数组节点的每个元素子元素添加新子元素
【发布时间】:2018-05-20 21:45:36
【问题描述】:

我的 xml 看起来像这样:

<ArrayOfConfig>
    <Config>
        <!--stuff-->
    </Config>
    <Config>
        <!--stuff-->
    </Config>
</ArrayOfConfig>

我需要用一个新的子节点填充每个 Config 节点,使其看起来像:

<ArrayOfConfig>
    <Config>
        <!--stuff-->
        <NewChild>foo</NewChild>
    </Config>
    <Config>
        <!--stuff-->
        <NewChild>foo</NewChild>
    </Config>
</ArrayOfConfig>

我已尝试运行以下 Powershell:

$doc = New-Object System.Xml.XmlDocument
$doc.Load('C:\temp\Configs.xml')
$child = $doc.CreateElement("NewChild")
$child.InnerText = "foo"
$doc.ArrayOfConfig.Config.AppendChild($child)
$doc.Save('C:\temp\Configs.xml')

运行这种工作,它只会将子节点添加到第二个配置中。示例:

<ArrayOfConfig>
    <Config>
        <!--stuff-->
    </Config>
    <Config>
        <!--stuff-->
        <NewChild>foo</NewChild>
    </Config>
</ArrayOfConfig>

ArrayOfConfigConfig 子节点的数量不同,所以我不能做任何静态赋值。如何遍历 ArrayOfConfig 的子节点并确保每个子节点都正确获取新的子节点?

【问题讨论】:

    标签: arrays xml powershell


    【解决方案1】:
    $doc = New-Object System.Xml.XmlDocument
    $doc.Load('C:\temp\Configs.xml')
    foreach($config in $doc.SelectNodes('//Config'))
    {
        $child = $doc.CreateElement("NewChild")
        $child.InnerText = "foo"
        $config.AppendChild($child)
    }
    $doc.Save('C:\temp\Configs.xml')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-14
      • 1970-01-01
      • 2021-03-20
      • 2020-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多