1

I'm having trouble with XDocument. What I need is to get the value of a node called "LocalityName" in this xml: http://maps.google.com/maps/geo?q=59.4344,24.3342&output=xml&sensor=false

I had this done using XmlDocument:

        XmlDocument doc = new XmlDocument();
        doc.Load("http://maps.google.com/maps/geo?q=54.9133,23.9001&output=xml&sensor=false");

        XmlNodeList myElement = doc.GetElementsByTagName("Locality");
        foreach (XmlNode node in myElement)
        {
            XmlElement myElement = (XmlElement)node;
            string varN = myElement.GetElementsByTagName("LocalityName")[0].InnerText;

Don't know if it's the best way, but it worked. Now I need to do the same with XDocument. I have been searching for the whole evening, but nothing works for me. Please point me out in the right direction. Thank you!

user1487309
  • 13
  • 1
  • 3

1 Answers1

4

Here are two ways using XDocument:

    XDocument doc = XDocument.Load("http://maps.google.com/maps/geo?q=54.9133,23.9001&output=xml&sensor=false");

    var localityName = doc.Descendants(XName.Get("LocalityName", @"urn:oasis:names:tc:ciq:xsdschema:xAL:2.0")).First().Value;

    var localityName2 = (from d in doc.Descendants()
                         where d.Name.LocalName == "LocalityName"
                         select d.Value).First();

The first method (localityName) assumes you know the namespace see https://stackoverflow.com/a/6209890/1207991 for more info.

The second method (localityName2) doesn't require the namespace see https://stackoverflow.com/a/2611152/1207991 for more info.

Community
  • 1
  • 1
Gloopy
  • 37,767
  • 15
  • 103
  • 71
  • Thank you! Works like a charm. But could you explain why you are using that weird namespace (urn:oasis:names:tc:ciq:xsdschema:xAL:2.0) instead of the first one? I spent my whole eveining trying to figure out how XDocument behaves, but with no luck. I guess it's too early for me :) – user1487309 Jun 28 '12 at 07:14
  • Aaand here is another problem. I can not use URL's with XDocument when developing for windows phone. But at the same time it's fine to do that in Visual C# 2010 for a desktop app. Why is that limitation created? – user1487309 Jun 28 '12 at 08:24
  • The XML sample from your URL has changed but I used the weird namespace because it was the namespace for the nearest ancestor node with a namespace (as opposed to the namespace of the root node which was http://earth.google.com/kml/2.0). I'm not too familiar with WP development but maybe this will help: http://stackoverflow.com/questions/5637773/windows-phone-7-reading-xml-with-xdocument – Gloopy Jun 28 '12 at 16:37