XPath 搜索 PowerShell 中的属性值 [英] XPath search on an attribute value in PowerShell

查看:35
本文介绍了XPath 搜索 PowerShell 中的属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管我在网上看到了这些示例,但似乎无法在 PowerShell 中对属性值进行 XPath 搜索.

[xml]$xml = '<a><b><c foo="bar"></c></b></a>'$xml |select-xml -xpath//c[@foo] # 这会返回一个节点$xml |select-xml -xpath//c[@foo='bar'] # 这个没有

我从来没有被这么简单的事情难住过.:-) 我怎样才能让它工作?

解决方案

如果你引用 xpath 它将工作正常:

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

这可能是因为 @ 是splat 运算符,所以它试图splat一个名为$foo的(不存在的)变量.

其实这个解释是错误的.显然是因为单引号.

如果你试试这个:

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

你会看到输出是:

<块引用>

//c[@foo=bar]

这似乎是因为 PowerShell 如何连接字符串.

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?

解决方案

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.

这篇关于XPath 搜索 PowerShell 中的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆