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
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);
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With