简体   繁体   English

XPath表达式中的Perl变量

[英]Perl variable in XPath expression

How can I use a Perl variable inside a XPath expression using the XML::LibXML module's findnodes() function? 如何使用XML :: LibXML模块的findnodes()函数在XPath表达式内使用Perl变量? This is what I got: 这就是我得到的:

my $variable = 1;
foreach my $node1 ($doc->findnodes('par/par1/par2[@id = $variable]'))
{

}

But it doesn't seem to work. 但这似乎不起作用。 Thanks. 谢谢。

You cannot interpolate using single quotes, you must use double quotes, or another form of quoting that does interpolate 您不能使用单引号进行插值,必须使用双引号或进行插值的另一种形式的报价

"par/par1/par2[\@id = $variable]"

However, I assume that @id is not a variable, so you must escape its sigil, or it will be treated as a variable as well. 但是,我假设@id不是变量,因此您必须转义其符号,否则也将其视为变量。 If you are using use strict -- which you always should -- this will lead to a compiler error. 如果您use strict (始终应该这样做),则将导致编译器错误。

The other forms of quoting that might be mentioned 可能提到的其他形式的报价

  • qq() , which is exactly like double quote qq() ,就像双引号一样
  • Heredocs Heredocs

edit: kudos to TLP 编辑:向TLP致敬

Haritz, 哈里兹,

Does changing the single quotes around the XPath expression to double quotes work? 将XPath表达式周围的单引号更改为双引号是否可行?

I came here looking for exactly the same solution and I tried it in one of my scripts and I think it works the same with double quotes instead of single quotes, but I'm interested to know if it works for you too. 我来到这里寻找完全相同的解决方案,并在我的一个脚本中进行了尝试,我认为它在使用双引号而不是单引号的情况下是相同的,但是我很想知道它是否也对您有用。

my $variable = 1;
foreach my $node1 ($doc->findnodes("par/par1/par2[\@id = $variable]"))
{

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM