如何在C#中从XmlNode获取参数值

4

如何获取XmlNode标签中参数的值。例如:

<weather time-layout="k-p24h-n7-1">
    <name>Weather Type, Coverage, and Intensity</name>
    <weather-conditions weather-summary="Mostly Sunny"/>
</weather>

我想要获取节点'weather-conditions'中参数'weather-summary'的值。
2个回答

7
var node = xmldoc.SelectSingleNode("weather/weather-conditions");
var attr = node.Attributes["weather-summary"];

4

为了完整起见,应该同时提供 .Net 3.5 的方式:

假设

XDocument doc = XDocument.Parse(@"<weather time-layout='k-p24h-n7-1'>
    <name>Weather Type, Coverage, and Intensity</name>
    <weather-conditions weather-summary='Mostly Sunny'/></weather>");

然后选择其中一种方式

return doc.Element("weather").Element("weather-conditions").Attribute("weather-summary").Value;

或者

return doc.Descendants("weather-conditions").First().Attribute("weather-summary").Value;

会给你相同的答案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接