开发者

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

开发者 https://www.devze.com 2022-12-10 07:12 出处:网络
My XML is: <CurrentWeather> <Location>Berlin</Location> </CurrentWeather> I want the s开发者_如何学Pythontring \"Berlin\", how do get contents out of the element Location, s

My XML is:

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

I want the s开发者_如何学Pythontring "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();
}


string location = doc.Descendants("Location").Single().Value;


string location = (string)xdoc.Root.Element("Location");


In a simple case with the single element,

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

string location = xDocument..Descendants("CurrentWeather").Element("Location").Value;

Multiple elements like this,

<CurrentWeather>
    <Location>Berlin</Location>
    <Location>Auckland</Location>
   <Location>Wellington</Location>
</CurrentWeather>

  foreach (var result in xDocument.Descendants("CurrentWeather").Select(x => new{ location = x.Element("Location").Value.Tostring() }))
        {
          Locations + = location ;
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消