如何在评估之前检查元素是否存在

时间:2015-07-24 09:59:07

标签: java xml dom xpath sax

下面发布的xml文件,如图所示它有两个名为" tag"的元素。我编写了下面的代码,以检索"标签中的值"基于lat和lon上的值。 我现在面临的问题是,尽管我正在处理的xml文件具有几乎相同的结构,但是其中一些有一个名为" tag"和其他人有"标签"的两个要素。 我的问题是,有没有办法在评估表达式之前使用xpath来检查元素是否存在?

这是我的尝试,但它不起作用:

"//node/[boolean(tag)]";
"//node/tag[boolean(@following-sibling::tag[1])]";

更新

what i want to do is, to check if the there exist a ::tag[1] and ::tag[2]    
before start evaluating the expression according to the given lat and lon   
"independent of the lat and lon". or in other words, how should i know the 
 number of "tag" exists

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="no"/>
</osm>

private String buildExpression0(double lat, double lon) {
    // TODO Auto-generated method stub
    return "//node[@lat='"+lat+"'"+"][@lon='"+lon+"']/following-sibling::tag[1]/@v";
}

private String buildExpression1(double lat, double lon) {
    // TODO Auto-generated method stub
    return "//node[@lat='"+lat+"'"+"][@lon='"+lon+"']/following-sibling::tag[2]/@v";
}

1 个答案:

答案 0 :(得分:0)

知道xml中tag个元素的数量,只需评估以下xpath:

count(//tag)