【问题标题】:Accessing XML element values with names 'name' and 'value'访问名称为“name”和“value”的 XML 元素值
【发布时间】: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 的根元素时,您发布的代码对这两种部分结构都很好。因此,问题很可能与您如何从实际数据中选择 &lt;ExtraAttributes&gt; 节点有关。
  • 如果您能取消对我的问题投反对票,我将不胜感激。我确实弄清楚了,尽管我从未发现根本原因。 $ExtraAttributes 元素是从根文档中提取的,格式如下:[xml]$config = Get-Content myfile.xml $ExtraAttributes = $config.Configuration.District.ExtraAttributes 如果有更好的方法,我想知道。

标签: xml powershell foreach


【解决方案1】:

我没有使用childNodes,而是使用了元素名称A

foreach ($att in ($ExtraAttributes.Attributes.A | where { [int]$_.Enabled -eq $true })) {
Write-Host "Name: $($att.name), Value: $($att.value)"
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多