首页 > 解决方案 > PowerShell 操作 XML - 向 XML 对象添加任意数据

问题描述

这是 API 调用的预定义变量。

$CorePluginConfigurationContext = ([xml]"
<CorePluginConfigurationContext xmlns='http://schemas.solarwinds.com/2012/Orion/Core' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>
    <BulkList>
        <IpAddress>
            <Address></Address>
        </IpAddress>
    </BulkList>
</CorePluginConfigurationContext>
").DocumentElement

阅读 PowerShell 书籍、在线文档、XML 命名空间、节点、父母、孩子、追加、“元素”、“s”,我根本无法将数据添加到这个特定的变量。

我得到多个值作为参数

Param(
    [Parameter(Mandatory=$true)]
    [String[]]$nodes = "1.1.1.1"
)

并且需要将这些值添加到 XML 对象中。

foreach ($node in $nodes) { }

结果如下所示:

<CorePluginConfigurationContext xmlns='http://schemas.solarwinds.com/2012/Orion/Core' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>
    <BulkList>
        <IpAddress>
            <Address>10.10.1.19</Address>
        </IpAddress>
        <IpAddress>
            <Address>10.10.1.20</Address>
        </IpAddress>
    </BulkList>
</CorePluginConfigurationContext>

测试代码:

Param (
    [Parameter(Mandatory=$true)]
    [String[]]$nodes = "1.1.1.1"
)

$CorePluginConfigurationContext = ([xml]"
<CorePluginConfigurationContext xmlns='http://schemas.solarwinds.com/2012/Orion/Core' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>
    <BulkList>
        <IpAddress>
            <Address></Address>
        </IpAddress>
    </BulkList>
</CorePluginConfigurationContext>
").DocumentElement

foreach ($node in $nodes) {
    # Code to add multiple $node values to the XML above
}

标签: xmlpowershell

解决方案


一方面,您应该将 XML文档分配给您的变量,而不仅仅是文档元素(即根节点):

$xml = [xml]"
<CorePluginConfigurationContext xmlns='http://schemas.solarwinds.com/2012/Orion/Core' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>
    <BulkList>
        <IpAddress>
            <Address></Address>
        </IpAddress>
    </BulkList>
</CorePluginConfigurationContext>"

这不是一个大问题,因为您可以通过 节点从节点获取文档$xml.OwnerDocument,但让变量保存实际文档对象仍然是更好的形式。

此外,如果您打算稍后添加数据,则不应将空节点放入文档中,因为您必须删除空节点或分配与所有其他值不同的值之一。

接下来,您的 XML 文档具有名称空间,因此您需要一个名称空间管理器。

$uri = 'http://schemas.solarwinds.com/2012/Orion/Core'
$nm = New-Object Xml.XmlNamespaceManager $xml.NameTable
$nm.AddNamespace('ns', $uri)

使用该命名空间管理器,您可以选择要附加到的节点:

$bulklist = $xml.SelectSingleNode('ns:BulkList', $nm)

然后循环输入值,为它们创建节点,并将它们附加到选定的父节点:

foreach ($node in $nodes) {
    $addr = $xml.CreateElement('Address', $uri)
    $addr.InnerText = $node

    $ip = $xml.CreateElement('IpAddress', $uri)
    [void]$ip.AppendChild($addr)

    [void]$bulklist.AppendChild($ip)
}

推荐阅读