0

好的,首先我完全了解这个问题“显示具有相同节点值的多个 XML 数据条目”,但它没有回答我的问题

好的,开始这是我的 xml

<xml_api_reply version="1">
  <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
  <forecast_conditions>
    <day_of_week data="Wed"/>
    <low data="57"/>
    <high data="68"/>
    <icon data="/ig/images/weather/partly_cloudy.gif"/>
    <condition data="Partly Cloudy"/>
  </forecast_conditions>
    <forecast_conditions>
      <day_of_week data="Thu"/>
      <low data="57"/>
      <high data="68"/>
      <icon data="/ig/images/weather/chance_of_rain.gif"/>
      <condition data="Chance of Rain"/>
    </forecast_conditions>
    <forecast_conditions>
      <day_of_week data="Fri"/>
      <low data="59"/>
      <high data="68"/>
      <icon data="/ig/images/weather/cloudy.gif"/>
      <condition data="Cloudy"/>
    </forecast_conditions>
    <forecast_conditions>
      <day_of_week data="Sat"/>
      <low data="59"/>
      <high data="68"/>
      <icon data="/ig/images/weather/cloudy.gif"/>
      <condition data="Cloudy"/>
    </forecast_conditions>
  </weather>
</xml_api_reply>

正如你所看到的那样,有多个forecast_conditions,我想要做的是每天在自己的字符串中显示,就像这样......

string day1;
string day2;
string day3;
string day4;

day1 = "Wed";
day2 = "Thu";
day3 = "Fri";
day4 = "Sat";

但由于所有的标题节点都是相同的(forecast_conditions)我有点困惑如何做到这一点

这就是我到目前为止得到它的方式

foreach (XmlNode node in xmlConditions.SelectNodes("/xml_api_reply/weather/forecast_conditions"))
{
    Conditions condition = new Conditions();
    condition.City = xmlConditions.SelectSingleNode("/xml_api_reply/weather/forecast_information/city").Attributes["data"].InnerText;
    condition.Condition = node.SelectSingleNode("condition").Attributes["data"].InnerText;
    condition.High = node.SelectSingleNode("high").Attributes["data"].InnerText;
    condition.Low = node.SelectSingleNode("low").Attributes["data"].InnerText;
    condition.DayOfWeek = node.SelectSingleNode("day_of_week").Attributes["data"].InnerText;
    conditions.Add(condition);
}

和这个

public class Conditions
{
    public string DayOfWeek
    {
        get { return dayOfWeek; }
        set { dayOfWeek = value; }
    }

等等

4

1 回答 1

0

如果您将 XML 存储在XDocument对象中,则可以使用 LINQ 执行此操作。我还没有完全测试过,但尝试这样的事情:

XDocument doc = XDocument.Load(stream_of_your_xml);
var allConditions = from forecast_conditions in doc.Descendants("forecast_conditions") 
            select new Conditions()
            {
                DayOfWeek = forecast_conditions.Element("day_of_week").Attribute("data").Value,
                Low = forecast_conditions.Element("low").Attribute("data").Value
                //Do the same for your other values
            };
List<Conditions> theConditions = (List<Conditions>) allConditions;
于 2013-04-30T22:46:51.870 回答