我的XML是:
<CurrentWeather>
<Location>Berlin</Location>
</CurrentWeather>
Run Code Online (Sandbox Code Playgroud)
我想要字符串"Berlin",如何从元素Location中获取内容,比如InnerText?
XDocument xdoc = XDocument.Parse(xml);
string location = xdoc.Descendants("Location").ToString();
Run Code Online (Sandbox Code Playgroud)
以上回报
System.Xml.Linq.XContainer + d__a
Ahm*_*eed 15
对于您的特定样品:
string result = xdoc.Descendants("Location").Single().Value;
Run Code Online (Sandbox Code Playgroud)
但是,请注意,如果您有更大的XML示例,则Descendants可以返回多个结果:
<root>
<CurrentWeather>
<Location>Berlin</Location>
</CurrentWeather>
<CurrentWeather>
<Location>Florida</Location>
</CurrentWeather>
</root>
Run Code Online (Sandbox Code Playgroud)
以上代码将更改为:
foreach (XElement element in xdoc.Descendants("Location"))
{
Console.WriteLine(element.Value);
}
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11628 次 |
| 最近记录: |