如何在xpath表达式中使用逻辑运算符

时间:2015-07-17 10:23:58

标签: java dom xpath sax

我编写了以下代码,通过指定vtag值来检索元素lat中的attribuet lon的值,如下所示。 我认为我的错误与我如何使用&&运算符在xpath表达式中,因为当我使用

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

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

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

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)

1 个答案:

答案 0 :(得分:12)

XPath中的布尔“和”运算符是单词and,而不是&&specification

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

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

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

这具有相同的效果 - 谓词从左到右应用,因此第一个谓词将所有node元素的集合过滤为仅有@lat='53.334062'的元素,第二个过滤器 设置为@lon='8.841545'