xml 在powershell中使用xpath选择xml中的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17583373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selecting attributes in xml using xpath in powershell
提问by user1044585
I am trying to use powershell and XPath to select the name attribute shown in the below xml example.
我正在尝试使用 powershell 和 XPath 来选择下面 xml 示例中显示的 name 属性。
$xml_peoples= $file.SelectNodes("//people")
foreach ($person in $xml_peoples){
echo $person.attributes
#echo $person.attributes.name
}
Above is the code im running to try and get the name, but it doesn't seem to work. Any suggestions?
上面是我运行以尝试获取名称的代码,但它似乎不起作用。有什么建议?
<peoples>
<person name='James'>
<device>
<id>james1</id>
<ip>192.192.192.192</ip>
</device>
</person>
</peoples>
Thanks in advance!
提前致谢!
采纳答案by Adi Inbar
I'm not sure what $hubis, and you started your code from the middle so it's not clear if you properly set $fileto an XmlDocument object, but I think this is what you want:
我不确定$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
}
回答by Ansgar Wiechers
These two lines should suffice:
这两行应该就足够了:
[xml]$xml = Get-Content 'C:\path\to\your.xml'
$xml.selectNodes('//person') | select Name
回答by CommonToast
How about one line?
一根线怎么样?
Select-XML -path "pathtoxml" -xpath "//person/@name"
Select-XML -path "pathtoxml" -xpath "//person/@name"
回答by John Neuhaus
For anyone that has to work around Select-Xml's garbage namespace handling, here's a one-liner that doesn't care, as long as you know the direct path:
对于必须解决 Select-Xml 的垃圾名称空间处理的任何人,只要您知道直接路径,这里有一个不关心的单行:
([xml](Get-Content -Path "path\to.xml")).Peoples.Person.Name
The above will return all matching nodes as well. It's not as powerful, but it's clean when you know the schema and want one thing out of it quickly.
以上也将返回所有匹配的节点。它没有那么强大,但是当您了解架构并希望快速从中获得一件事时,它是干净的。

