【问题标题】:How to select an attribute in XML based on the value of another attribute?如何根据另一个属性的值在 XML 中选择一个属性?
【发布时间】:2015-01-24 12:13:59
【问题描述】:

目前我可以在 XML 文档中选择属性,因为它们是唯一可识别的,如下所示:

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)中选择“文本”属性?

<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”?

【问题讨论】:

  • "yweather:location[@day = 'mon']/@city"

标签: c# xml linq


【解决方案1】:

这样的事情会起作用:

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 post

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-29
    • 1970-01-01
    • 2014-08-04
    相关资源
    最近更新 更多