xml - 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
}
解决方案
一方面,您应该将 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)
}
推荐阅读
- c# - DevExpress 集合过滤器和BetweenOperator
- django - 使用 MongoDB 在 Django Admin 中记录主键错误
- vue.js - 如何正确设置产品的 sw-entity-multi-select 字段并将它们保存到您的扩展
- multimap - c++ std::multi_map 迭代equal_range问题
- flutter - 如何在 gridview.builder 中通过 Tabbar 导航?
- php - 如何在资源 laravel 中显示分页链接
- reactjs - reactjs - 如何在reactjs的material-UI多选框中将默认值设置为选中?
- mysql - MySQL 8.0 - 用户定义的函数在其主体 (STR_TO_DATE) 生成的警告上崩溃
- c++ - 从文件中读取数组并将它们存储到结构成员中
- flutter - 输入'未来
- >' 不是类型“列表”的子类型
' 在类型转换中