检索标记值会导致无限循环

时间:2015-12-10 12:13:09

标签: java xml xpath xml-parsing

在下面发布的xml文件中我试图显示标签元素的值属于

<node id="125801" lat="53.0705997" lon="8.7818627">

我写了下面的代码,但它进入无限循环

为什么会发生这种情况以及如何解决?

xml文件

<?xml version='1.0' encoding='UTF-8'?>
<osm version="0.6" generator="osmconvert 0.7T" timestamp="2014-11-27T21:22:02Z">
<bounds minlat="53.01034" minlon="8.480959" maxlat="53.61063" maxlon="8.991268"/>
<node id="125799" lat="53.0749415" lon="8.7868047"/>
<node id="125800" lat="53.071932" lon="8.7840591"/>
<node id="125801" lat="53.0705997" lon="8.7818627"> // <====this one
    <tag k="highway" v="motorway_junction"/>
    <tag k="name" v="Bremen-Neustadt"/>
</node>
<node id="20973856" lat="53.0979621" lon="8.8667934"/>
<node id="20973857" lat="53.0976313" lon="8.868052"/>
<node id="20973858" lat="53.0974051" lon="8.86891"/>
<node id="20973859" lat="53.0972418" lon="8.8694694"/>
<node id="20973860" lat="53.0933247" lon="8.8705933"/>
<node id="20973861" lat="53.0935016" lon="8.8706564"/>
<node id="20973894" lat="53.1002332" lon="8.8842715"/>
<node id="20973895" lat="53.099723" lon="8.8858872">
    <tag k="highway" v="traffic_signals"/>
</node>
</osm>

for (int i = 1 ; i <= 2; i++) {
        String expr0 = "//node[@lat='53.0705997'][@lon='8.7818627']/following-sibling::tag["+i+"]/@v";
        xPath.compile(expr0);
        String s = (String) xPath.evaluate(expr0, document, XPathConstants.STRING);
        System.out.println(s);
    }
}

2 个答案:

答案 0 :(得分:1)

我发现在发布的代码片段中,循环无法进入。除此之外,您的XPath没有正确对应XML,即tag 不是following-sibling元素的 node,它是{{而不是child元素的1}}:

node
或者简单地说,就像大多数人一样:

String expr0 = "//node[@lat='53.0705997'][@lon='8.7818627']/child::tag["+i+"]/@v";

答案 1 :(得分:0)

如果你想要你的标签,这就足够了:

String expression="//node[@id=125801]";

和孩子们:

String expression="//node[@id=125801]/*";

对于迭代:

String expression="//node[@id=125801]";


NodeList nodes  = (NodeList)  xPath.compile(expression).evaluate(document, XPathConstants.NODESET);

for(int i=0; i<nodes.getLength(); i++)
{
 Node the_node = nodes.item(i);

 if(the_node instanceof Element)
    {
    Element element=(Element) the_node;
    // get what you want

希望有所帮助