简体   繁体   English

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

[英]How to get parameter values from an XmlNode in C#

How do I get the values for parameters in a XmlNode tag. 如何获取XmlNode标记中的参数值。 For example: 例如:

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

I want to get the value for the parameter 'weather-summary' in the node 'weather-conditions'. 我想在节点'weather-conditions'中获取参数'weather-summary'的值。

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

In the interest of completeness, the .Net 3.5 way should be given as well: 为了完整性,还应该给出.Net 3.5方式:

Assuming 假设

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>");

Then either 然后

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

Or 要么

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

Will give you the same answer. 会给你相同的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM