Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent to InnerText in LINQ-to-XML?

Tags:

c#

linq-to-xml

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

like image 459
Edward Tanguay Avatar asked Nov 03 '09 15:11

Edward Tanguay


2 Answers

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);
}
like image 76
Ahmad Mageed Avatar answered Nov 16 '22 23:11

Ahmad Mageed


public static string InnerText(this XElement el)
{
    StringBuilder str = new StringBuilder();
    foreach (XNode element in el.DescendantNodes().Where(x=>x.NodeType==XmlNodeType.Text))
    {
        str.Append(element.ToString());
    }
    return str.ToString();
}
like image 20
ikutsin Avatar answered Nov 16 '22 23:11

ikutsin