tags:

views:

315

answers:

4

My XML is:

<CurrentWeather>
  <Location>Berlin</Location>
</CurrentWeather>

I want the string "Berlin", how do get contents out of the element Location, something like InnerText?

XDocument xdoc = XDocument.Parse(xml);
string location = xdoc.Descendants("Location").ToString();

the above returns

System.Xml.Linq.XContainer+d__a

+3  A: 

For your particular sample:

string result = xdoc.Descendants("Location").Single().Value;

However, note that Descendants can return multiple results if you had a larger XML sample:

<root>
 <CurrentWeather>
  <Location>Berlin</Location>
 </CurrentWeather>
 <CurrentWeather>
  <Location>Florida</Location>
 </CurrentWeather>
</root>

The code for the above would change to:

foreach (XElement element in xdoc.Descendants("Location"))
{
    Console.WriteLine(element.Value);
}
Ahmad Mageed
I had tried that and was getting an error on Single(), turned out I had "using System.Xml.Linq" but forgot "using System.Linq", thanks.
Edward Tanguay
np, it happens :)
Ahmad Mageed
A: 

Here is a nice tutorial

http://blogs.techrepublic.com.com/programming-and-development/?p=594

madan
A: 
string location = doc.Descendants("Location").Single().Value;
bruno conde
A: 
string location = (string)xdoc.Root.Element("Location");
Mehdi Golchin