Get sibling values based on a single node's value from an XML document

140 views Asked by At

I want to loop through these results (right now there are 2, but there may be up to 100 in some cases). When I find a match on a specific value for the countrycode within a <doc> node, I want to select the latitude and longitude values from that same <doc> node.

e.g. when I'm searching for countrycode value 'US', I want to return the values -79.0236 and 35.1379, the respective longitude and latitude.

I'm trying to do it in ASP.NET where the XML below is loaded into an XMLDocument variable objXML.

I know how to select the countrycode, but not how to get the related latitude and longitude nodes.

objXML.SelectSingleNode("//response/result/doc/str[@name='US']").InnerText

<response>
    <lst name="responseHeader">
        <int name="status">0</int>
        <int name="QTime">3</int>
        <lst name="params">
            <str name="facet">false</str>
            <str name="fl">id,geonameid,title,latitude,longitude,countrycode</str>
            <str name="indent">off</str>
            <str name="start">0</str>
            <str name="q">title_search:*nijmegen*</str>
            <str name="rows">10</str>
            <str name="defType">lucene</str>
        </lst>
    </lst>
    <result name="response" numFound="2" start="0">
        <doc>
            <str name="countrycode">US</str>
            <str name="title">Nijmegen</str>
            <str name="longitude">-79.0236</str>
            <str name="geonameid">4482161.0</str>
            <str name="latitude">35.1379</str>
        </doc>
        <doc>
            <str name="countrycode">NL</str>
            <str name="title">nijmegen</str>
            <str name="longitude">5.85278</str>
            <str name="geonameid">2750053.0</str>
            <str name="latitude">51.8425</str>
        </doc>
    </result>
</response>
1

There are 1 answers

3
smj On BEST ANSWER

I don't think your XPath would work, there is no str element with a @name ='US'. But with Xpath 2.0 you could try:

//response/result/doc/str[@name="countrycode"][.='US']/../(str[@name="longitude"] | str[@name="latitude"])