C# extracting data from XML

偶尔善良 提交于 2019-11-29 02:08:20

Use LINQ to XML

XDocument X = XDocument.Load("http://www.yr.no/place/Norway/Oslo/Oslo/Oslo/forecast.xml");

var forecast = X.Element("weatherdata").Element("forecast");
var location = forecast.Descendants("location").Attributes("name").FirstOrDefault().Value;
var tempData = forecast.Element("tabular").Elements("time");

//This is what you need
var data = tempData.Select(item=>
            new{
                from = Convert.ToDateTime(item.Attribute("from").Value),
                to = Convert.ToDateTime(item.Attribute("to").Value),
                temp = item.Element("temperature").Attribute("value").Value
            });


//Or you can do a foreach if you need to
foreach (var item in tempData)
{
        DateTime from = Convert.ToDateTime(item.Attribute("from").Value);
        var temp = item.Element("temperature").Attribute("value").Value;
}

I haven't populated everything. I hope you get the idea of how to use it.

Use the XElement from System.Xml.Linq

XElement all = XElement.Load(reader);
var values = all.Decentents("forecast").Select(fc => {
     XElement time = fc.Element("time");
     XElement temp = fc.Element("temperature");
     return new Tuple<string, string, string, string>(
                  time.Attribute("from").Value,
                  time.Attribute("to").Value,
                  temperature.Attribute("unit").Value,
                  temperature.Attribute("value").Value);});

This may help you access specific node values as you seem to be wanting. Hope it helps!

Getting specified Node values from XML document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!