问题
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