XPath:将函数应用于所有匹配?

时间:2016-07-15 16:23:26

标签: xpath

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

//ElementName/@AttributeName

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

string(//ElementName/@AttributeName)

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

//ElementName/string(./@AttributeName)

但是这给我一个语法错误,我尝试的变化也是如此。所以目前,我正在这样做:

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

似乎......效率低下,至少。还有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

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

相关问题