2010-03-25 50 views
4

如何獲取XmlNode標記中參數的值。例如:如何從C#中的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'的值。

回答

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

完美。謝謝! – Brian 2010-03-25 03:38:40

3

在完整的利益時,.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; 

會給你同樣的答案。