【问题标题】:How to check if an element exist or not before the evaluation如何在评估之前检查元素是否存在
【发布时间】:2015-10-14 22:50:40
【问题描述】:

下面发布的 xml 文件,如图所示,它有两个称为“标签”的元素。我编写了以下代码,以根据 lat 和 lon 上的值检索“标签”中的值。 我现在面临的问题是,尽管我正在处理的 xml 文件具有几乎相同的结构,但其中一些文件有一个名为“tag”的元素,而另一些则有两个“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";
}

【问题讨论】:

  • 在每种情况下你想做什么?查看您发布的 2 种方法,难道不是只有一种方法吗,例如:获取最后一个标签(如果有 2 个标签,则为第 2 个标签,否则为第 1 个标签)?
  • @har07 请看更新

标签: java xml dom xpath sax


【解决方案1】:

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

count(//tag)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-02
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 2012-11-20
    相关资源
    最近更新 更多