如何基于另一个属性的值选择XML中的属性? [英] How to select an attribute in XML based on the value of another attribute?
本文介绍了如何基于另一个属性的值选择XML中的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当前,我能够在XML文档中选择属性,因为它们是唯一可识别的,如下所示:
Currently I am able to select attributes in an XML document because they are uniquely identifiable, like this:
XmlDocument weatherData = new XmlDocument();
weatherData.Load(query);
XmlNode channel = weatherData.SelectSingleNode("rss").SelectSingleNode("channel");
XmlNamespaceManager man = new XmlNamespaceManager(weatherData.NameTable);
man.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
town = channel.SelectSingleNode("yweather:location", man).Attributes["city"].Value;
但是如何从同名的节点(yweather:forecast)中选择文本"属性?
But how do I select the "text" attribute from a node of the same name (yweather:forecast)?
<yweather:forecast day="Sat" text="Sunny" code="32"/>
<yweather:forecast day="Sun" text="Partly Cloudy" code="30"/>
<yweather:forecast day="Mon" text="AM Showers" code="39"/>
<yweather:forecast day="Tue" text="Cloudy" code="26"/>
<yweather:forecast day="Wed" text="Cloudy/Wind" code="24"/>
是否有一条条件语句只能用于选择text
属性(其中day
属性等于"Mon")?
Is there a conditional statement I can use to only select the text
attribute where the day
attribute is equal to "Mon"?
推荐答案
类似的方法将起作用:
string xml = "YourXml";
XElement doc = XElement.Parse(xml);
var Result = from a in doc.Descendants("yweather:forecast")
where a.Attribute("day").Value == "Mon"
select a.Attribute("text").Value;
或lambda语法:
var Result = doc.Descendants("yweather:forecast")
.Where(x=> x.Attribute("day").Value == "Mon")
.Select(x=> x.Attribute("text").Value);
您还可以参考此 SO帖子
这篇关于如何基于另一个属性的值选择XML中的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文