如何根据另一个属性的值 select XML 中的一个属性?
How to select an attribute in XML based on the value of another attribute?
目前我能够 select 文档中的属性,因为它们是唯一可识别的,如下所示:
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;
但是我如何 select 来自同名节点 (yweather:forecast) 的 "text" 属性?
<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"/>
是否有条件语句我可以仅用于 select text
属性,其中 day
属性等于 "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);
你也可以参考这个
目前我能够 select 文档中的属性,因为它们是唯一可识别的,如下所示:
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;
但是我如何 select 来自同名节点 (yweather:forecast) 的 "text" 属性?
<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"/>
是否有条件语句我可以仅用于 select text
属性,其中 day
属性等于 "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);
你也可以参考这个