显示具有相同节点值的XML数据项

本文关键字:XML 数据项 节点 显示 | 更新日期: 2023-09-27 18:11:30

首先我完全意识到这个问题"显示多个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; }
    }

等等

显示具有相同节点值的XML数据项

如果您将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;