Reputation: 13
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!
Upvotes: 1
Views: 3152
Reputation: 37785
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.
Upvotes: 4