如何在XPath表达式中使用逻辑运算符 [英] How to use logical operator in xpath expression

查看:456
本文介绍了如何在XPath表达式中使用逻辑运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下代码,通过在 tag 元素中检索属性 v 在元素 tag 中的值。 code> lat 和 lon 值,如下所示。
我认为我的错误与我如何使用&& xpath表达式中的运算符,因为当我使用

i wrote the beloww code to retrive the value of the attribuet v in the element tag by specifyin the lat and lon values as shown below. i think my mistake is related to the how i use the && operator in the xpath expression, because when i used

String expr0 = "//node[@lat='53.334062']/following-sibling::tag[1]/@v";

我收到了期望值,但是当我使用下面的表达式时,系统崩溃

i receive the expected value, but when i uesd the below posted expression, the system crashs

,但是在运行时,程序崩溃并显示以下错误消息。

but at run time, the program crashs and shows the below error message.

代码

String expr0 = "//node[@lat='53.334062' && @lon='8.841545']/following-sibling::tag[1]/@v";
    xPath.compile(expr0);
    String s = (String) xPath.evaluate(expr0, document, XPathConstants.STRING);
    System.out.println(s);

xml

<?xml version='1.0' encoding='utf-8' ?>
<osm>
<node id="25779111" lat="53.0334062" lon="8.8461545"/>
<node id="25779112" lat="53.0338904" lon="8.846314"/>
<node id="25779119" lat="53.0337395" lon="8.8489255"/>
<tag k="maxspeed" v="30"/>
<tag k="maxspeed:zone" v="yes"/>
<node id="25779114" lat="53.334062" lon="8.841545"/>
<node id="25779117" lat="53.038904" lon="8.84614"/>
<node id="25779110" lat="53.033795" lon="8.489255"/>
<tag k="maxspeed" v="32"/>  
<tag k="maxspeed:zone" v="yes"/>
</osm>

错误

Exception in thread "main" javax.xml.transform.TransformerException: Zusätzliche ungültige Tokens: '&&', '[', '@', 'lon', '=', ''8.841545'', ']', '/', 'following-sibling', '::', 'tag', '[', '1', ']', '/', '@', 'v'
at com.sun.org.apache.xpath.internal.compiler.XPathParser.error(Unknown Source)
at com.sun.org.apache.xpath.internal.compiler.XPathParser.initXPath(Unknown Source)
at com.sun.org.apache.xpath.internal.XPath.<init>(Unknown Source)
at com.sun.org.apache.xpath.internal.XPath.<init>(Unknown Source)
at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.compile(Unknown Source)


推荐答案

XPath中的布尔和运算符是和,而不是& 规范

The Boolean "and" operator in XPath is the word and, not && (specification)

String expr0 = "//node[@lat='53.334062' and @lon='8.841545']/following-sibling::tag[1]/@v";

或者,您可以使用两个谓词:

Alternatively you can use two predicates:

String expr0 = "//node[@lat='53.334062'][@lon='8.841545']/following-sibling::tag[1]/@v";

这具有相同的效果-谓词从左到右应用,因此第一个谓词过滤所有谓词将 node 元素更改为具有 @ lat = '53 .334062'的元素,第二个过滤器 that 设置为仅具有 @ lon ='8.841545'的那些。

This has the same effect - predicates apply from left to right so the first predicate filters the set of all node elements to just those that have @lat='53.334062', the second filters that set to just those that have @lon='8.841545'.

这篇关于如何在XPath表达式中使用逻辑运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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