【发布时间】:2015-12-23 18:49:45
【问题描述】:
在 PowerShell 中,给定以下部分 XML 结构:
<ExtraAttributes Enabled="1" PerBuildingEnabled="0" PerBuildingMode="0">
<!--PerBuildingMode 0: Inclusively district and building, Mode 1: Exclusively building-->
<Attributes>
<A Enabled="1">
<name>mail</name>
<value>$UserPrincipalName</value>
</A>
<A Enabled="1">
<name>ipPhone</name>
<value>123456</value>
</A>
</Attributes>
</ExtraAttributes>
如果我尝试使用以下内容访问value 元素之一的值:
# $ExtraAttributes is extracted as [Xml.XmlElement] from an [Xml.XmlDocument]
foreach ($att in ($ExtraAttributes.Attributes.ChildNodes | where { [int]$_.Enabled -eq $true })) {
Write-Host "Name: $($att.name), Value: $($att.value)"
}
它工作得很好......但是,如果Attributes 下只有一个A 元素,就像这样:
<ExtraAttributes Enabled="1" PerBuildingEnabled="0" PerBuildingMode="0">
<!--PerBuildingMode 0: Inclusively district and building, Mode 1: Exclusively building-->
<Attributes>
<A Enabled="1">
<name>mail</name>
<value>$UserPrincipalName</value>
</A>
</Attributes>
</ExtraAttributes>
Powershell 认为 $att.value 是 $null。
当只有一个 A 元素出现在同一个 foreach 循环中时,如何访问这些元素值? XML 可以重组,但我试图避免这种情况。
【问题讨论】:
-
当我将
$ExtraAttributes设置为 XML sn-p 的根元素时,您发布的代码对这两种部分结构都很好。因此,问题很可能与您如何从实际数据中选择<ExtraAttributes>节点有关。 -
如果您能取消对我的问题投反对票,我将不胜感激。我确实弄清楚了,尽管我从未发现根本原因。
$ExtraAttributes元素是从根文档中提取的,格式如下:[xml]$config = Get-Content myfile.xml$ExtraAttributes = $config.Configuration.District.ExtraAttributes如果有更好的方法,我想知道。
标签: xml powershell foreach