1

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 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.