Search code examples
javadomxpathsax

How to link between two different elements


in the below posted xml file, the element "tag" contains speed info. the problem i am facing is that, the first two elements "node"

<node id="25779111" lat="53.0334062" lon="8.8461545"/>
<node id="25779112" lat="53.0338904" lon="8.846314"/>

their speed info is enclosed in the immediate proceeding two elements "tag"

<tag k="maxspeed" v="30"/>  
<tag k="maxspeed:zone" v="yes"/>

and the second two element "node":

<node id="25779114" lat="53.334062" lon="8.841545"/>
<node id="25779117" lat="53.038904" lon="8.84614"/>

their speed info is enclosed in the immediate proceeding two elements "tag"

<tag k="maxspeed" v="32"/>  
<tag k="maxspeed:zone" v="yes"/>

what i want to do is, given the information of the "lat" attribute, the speed information should be returned. for an example, if the input is either lat="53.0334062" or lat="53.0338904" the returned values should be v="30". and if the input is either lat="53.334062" or lat="53.038904 the returned values should be v="32"

how can i achive that using xpath?

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"/>
<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"/>
<tag k="maxspeed" v="32"/>  
<tag k="maxspeed:zone" v="yes"/>
</osm>

Solution

  • use this

    //node[@lat="53.0334062"]/following-sibling::tag[1]/@v
    
    //node[@lat="**yourinput**"]/following-sibling::tag[1]/@v
    

    explanation:

    node[@lat="53.0334062"] matches your condition. then, following-sibling fetches all child's in the node element, within that elements it will select the first tag element, indeed that is the element you require to get the attribute 'V'.