How to use logical operator in xpath expression

半腔热情 提交于 2020-08-23 07:05:29

问题


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.

code:

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>

error:

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:


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";

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'.



来源:https://stackoverflow.com/questions/31473666/how-to-use-logical-operator-in-xpath-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!