Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

c# - Unable to get value from Descendants() or Element() using XML

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...