XPath:将函数应用于所有匹配项? [英] XPath: apply function to all matches?

查看:32
本文介绍了XPath:将函数应用于所有匹配项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个 XPath 表达式来获取我感兴趣的属性值:

So I have an XPath expression to get at the attribute value I'm interested in:

//ElementName/@AttributeName

我只想要该属性的值作为字符串.我可以这样做:

I want just the value of that attribute as a string. I can do this:

string(//ElementName/@AttributeName)

但这仅将函数应用于第一个节点.我想获得将 string() 应用到 all 的匹配结果,并连接在一起(我从命令行使用 xmllint,它只是打印出表达式的结果,因此它不需要是结构化类型的结果).我认为这可能有效:

but that only applies the function to the first node. I want to get the result of applying string() to all of the matches, concatenated together (I'm using xmllint from the command line, which just prints out the results of the expression, so it doesn't need to be a structured type result). I thought this might work:

//ElementName/string(./@AttributeName)

但这给了我一个语法错误,就像我尝试的变体一样.所以目前,我正在这样做:

But that gives me a syntax error, as do the variations I tried. So at the moment, I'm doing this:

count=$(xmllint --xpath 'count(//ElementName/@AttributeName)' file.xml)
for (( i=1; i<=count; ++i )); do
   echo "$(xmllint --xpath "string((//ElementName/@AttributeName)[$i])" file.xml)"
done

这似乎……效率低下,至少.有没有更好的办法?

which seems ... inefficient, at least. Is there a better way?

推荐答案

在 XPath 2.0(或 XQuery 1.0)及更高版本中,您可以使用 //ElementName/@AttributeName/string() 的方法获取所有字符串值的序列或 string-join(//ElementName/@AttributeName, '') 将它们连接在一起.但是在 XPath 1.0 中,您总是需要像以前一样使用宿主语言.

With XPath 2.0 (or XQuery 1.0) and later you can use the approach of //ElementName/@AttributeName/string() to get a sequence of all string values or string-join(//ElementName/@AttributeName, '') to concatenate them all together. But in XPath 1.0 you always need to go to the host language as you have done.

这篇关于XPath:将函数应用于所有匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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