LINQ-to-XML中的InnerText相当于什么?

时间:2009-11-03 15:22:58

标签: c# linq-to-xml

我的XML是:

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

我想要字符串“Berlin”,如何从元素位置中获取内容,如 InnerText

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

以上返回

  

System.Xml.Linq.XContainer + d__a

5 个答案:

答案 0 :(得分:15)

对于您的特定样本:

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

但是,请注意,如果您拥有更大的XML示例,则Descendants可以返回多个结果:

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

上述代码将更改为:

foreach (XElement element in xdoc.Descendants("Location"))
{
    Console.WriteLine(element.Value);
}

答案 1 :(得分:1)

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();
}

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

在单个元素的简单情况下,

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

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

像这样的多个元素,

<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 ;
        }