XPath search on an attribute value in PowerShell

烈酒焚心 提交于 2020-01-06 02:24:24

问题


Despite the examples I've seen online, it doesn't seem to be possible to do an XPath search on an attribute value in PowerShell.

[xml]$xml = '<a><b><c foo="bar"></c></b></a>'
$xml | select-xml -xpath //c[@foo]  # This returns a node
$xml | select-xml -xpath //c[@foo='bar'] # This does not

I've never been so stumped by something so simple. :-) How can I get this to work?


回答1:


If you quote the xpath it will work fine:

[xml]$xml = '<a><b><c foo="bar"></c></b></a>'
$xml | select-xml -xpath "//c[@foo='bar']"

This is probably because @ is the splat operator, so it's trying to splat a (non-existant) variable named $foo.

Actually that explanation is wrong. It's apparently because of the single quotes.

If you try this:

Write-Host //c[@foo='bar']

You'll see that the output is:

//c[@foo=bar]

It seems this is because of how PowerShell concatenates strings.



来源:https://stackoverflow.com/questions/36264788/xpath-search-on-an-attribute-value-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!