Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I can't seem to get a value from child nodes of an xml file. I feel like I have tried everything. All I want is to get the value of latitude and longitude of the location child node in the xml file. What am I doing wrong? Maybe I should try JSON instead of XML.

private void RequestCompleted(IAsyncResult result)
{
    var request = (HttpWebRequest)result.AsyncState;
    var response = (HttpWebResponse)request.EndGetResponse(result);
    StreamReader stream = new StreamReader(response.GetResponseStream());

    try
    {
        XDocument xdoc = XDocument.Load(stream);
        XElement root = xdoc.Root;
        XNamespace ns = xdoc.Root.Name.Namespace;

        List<XElement> results = xdoc.Descendants(ns + "GeocodeResponse").Descendants(ns + "result").ToList();
        List<XElement> locationElement = results.Descendants(ns + "geometry").Descendants(ns + "location").ToList();
        List<XElement> lat = locationElement.Descendants(ns + "lat").ToList();
        List<XElement> lng = locationElement.Descendants(ns + "lng").ToList();
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error" + ex.Message)
    }
}

xml

<GeocodeResponse>
    <status>OK</status>
    <result>
        <type>street_address</type>
        <formatted_address>134 Gearger Circle, Lexington, KY, USA</formatted_address>
    <geometry>
        <location>
            <lat>36.31228546</lat>
            <lng>-91.4444399</lng>
        </location>
        <location_type>ROOFTOP</location_type>
    </geometry>
    <place_id>ChIJtwDV05mW-IgRyJKZ7fjmYVc</place_id>
    </result>
</GeocodeResponse>

Also here is a debug value that shows a count of zero. not sure what that means. I just need the value of lat and lng.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
151 views
Welcome To Ask or Share your Answers For Others

1 Answer

If I understand your question correctly you are looking for the list of all the lat and lng in the XML Document.

XDocument xdc = XDocument.Load(stream);
var AllLats = xdc.Descendants("lat");
var AllLong = xdc.Descendants("lng");

You wont need to drill down to the hierarchy to get the XML Nodes value with Descendants

Another part is ns that is your namespace has to be included for the XML which looks like

<SOmeNS:address_component>

not for the elements which does have name without :

attaching the screenshot to see if you want this output.

ScreenShot


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...