访问名为“name”和“value”的XML元素值

访问名为“name”和“value”的XML元素值,xml,powershell,foreach,Xml,Powershell,Foreach,在PowerShell中,给定以下部分XML结构: 邮政 $UserPrincipalName ipPhone 123456 如果我尝试通过以下方式访问某个值元素的值: $ExtraAttributes从[Xml.XmlDocument]提取为[Xml.xmlement] $ExtraAttributes.Attributes.ChildNodes中的foreach$att |其中{[int]$\已启用-eq$true}{ 写入主机名:$$att.Name,值:$$att.Value } 它工作

在PowerShell中,给定以下部分XML结构:

邮政 $UserPrincipalName ipPhone 123456 如果我尝试通过以下方式访问某个值元素的值:

$ExtraAttributes从[Xml.XmlDocument]提取为[Xml.xmlement] $ExtraAttributes.Attributes.ChildNodes中的foreach$att |其中{[int]$\已启用-eq$true}{ 写入主机名:$$att.Name,值:$$att.Value } 它工作得很好…但是,如果在如下属性下只有一个a元素:

邮政 $UserPrincipalName Powershell认为$att.value为$null

当同一foreach循环中只存在单个a元素时,如何访问这些元素值?XML可以重新构造,但我正试图避免这种情况。

我没有使用childNodes,而是使用元素名A,如下所示:


无论只有一个或多个A元素,它都能按预期工作。我一直不明白为什么childNodes不允许它工作。

当我将$ExtraAttributes设置为任意一个XML片段的根元素时,您发布的代码对这两个部分结构都可以正常工作。因此,问题很可能是如何从实际数据中选择节点。如果您能取消对我的问题的投票,我将不胜感激。虽然我从未发现根本原因,但我确实找到了答案。$ExtraAttributes元素是以以下格式从根文档中提取的:[xml]$config=Get Content myfile.xml$ExtraAttributes=$config.Configuration.District.ExtraAttributes如果有更好的方法,我想知道。
foreach ($att in ($ExtraAttributes.Attributes.A | where { [int]$_.Enabled -eq $true })) {
Write-Host "Name: $($att.name), Value: $($att.value)"
}