【问题标题】:Selecting attributes in xml using xpath in powershell在powershell中使用xpath选择xml中的属性
【发布时间】:2013-07-09 03:13:30
【问题描述】:

我正在尝试使用 powershell 和 XPath 来选择下面 xml 示例中显示的名称属性。

     $xml_peoples= $file.SelectNodes("//people") 
     foreach ($person in $xml_peoples){
            echo $person.attributes
            #echo $person.attributes.name
     }

上面是我正在运行的代码来尝试获取名称,但它似乎不起作用。有什么建议吗?

<peoples>
    <person name='James'>
        <device>
            <id>james1</id>
            <ip>192.192.192.192</ip>
        </device>
    </person>
</peoples>

提前致谢!

【问题讨论】:

  • 是错字吗?您的 xpath 有“人”,因为您没有具有该名称的 XML 节点......它应该是“人”吗?
  • 请注明“似乎不起作用”。究竟发生了什么?我想我知道你预期会发生什么,但也可以指定这一点。

标签: xml powershell xpath scripting


【解决方案1】:

对于必须解决 Select-Xml 的垃圾命名空间处理的任何人,只要您知道直接路径,这里有一个不关心的单行代码:

([xml](Get-Content -Path "path\to.xml")).Peoples.Person.Name

上面也将返回所有匹配的节点。它没有那么强大,但是当您知道架构并想要快速从中得到一件事时,它就很干净了。

【讨论】:

    【解决方案2】:

    一行呢?

    Select-XML -path "pathtoxml" -xpath "//person/@name"

    【讨论】:

    • 如果不是因为 Select-XML 对名称空间的粗暴处理,那将是完美的。您需要为路径中的每个元素添加一个命名空间参数(如果它像大多数一样使用默认 xmlns,则使用一个虚拟命名空间名称)。如果您不提前知道命名空间值,它就不再是单行(或至少是可读的)。
    【解决方案3】:

    这两行就足够了:

    [xml]$xml = Get-Content 'C:\path\to\your.xml'
    $xml.selectNodes('//person') | select Name
    

    【讨论】:

    • 如何将目录中的所有 xml 文件转换为 Powershell 中的 xml 对象?如 $path = get-childitem -filter *.xml (foreach $file in $path) {...#what goes here}
    • 如果您有新问题:请发布新问题。不要在 cmets 中跟进别人的问题。
    • 对不起,我已经发布了一个新问题stackoverflow.com/questions/42561059/…
    【解决方案4】:

    我不确定 $hub 是什么,您的代码从中间开始,因此不清楚您是否将 $file 正确设置为 XmlDocument 对象,但我认为这就是你想要的:

    [System.Xml.XmlDocument]$file = new-object System.Xml.XmlDocument
    $file.load(<path to XML file>)
    $xml_peoples= $file.SelectNodes("/peoples/person")
    foreach ($person in $xml_peoples) {
      echo $person.name
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      • 2016-01-14
      • 2018-11-26
      • 2014-01-30
      • 1970-01-01
      • 2014-12-09
      • 2014-08-19
      相关资源
      最近更新 更多