Originally Posted by
pianorain
I'd like to see that single line of code that reads an XML file and converts it into a collection of data objects. It's not immediately obvious from the documentation link you posted.
Hi Pianorain. I've thrown together an example which fits the context of argv's criteria.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace ConsoleApplication3
{
class TheObject
{
// going by the criteria mentioned in one of argv's replies
public DateTime Timestamp;
public int Number1;
public decimal Number2;
public String String1;
public String String2;
}
class Program
{
static void Main(string[] args)
{
List<TheObject> my_list = new List<TheObject>();
// let's add a few entries to the list
for (int i = 0; i < 20; i++)
my_list.Add(new TheObject
{
Timestamp = DateTime.Now,
Number1 = i,
Number2 = i,
String1 = ("string1 " + i),
String2 = ("string2 " + i)
});
// save the list into a xml document
SaveToXml(ref my_list);
// ok so now we have a xml document...
// let's clear the list and repopulate it from the xml document...
my_list = new List<TheObject>();
LoadFromXml(ref my_list);
}
static void SaveToXml(ref List<TheObject> list)
{
XDocument xml = new XDocument(new XElement("MyXMLFile"));
foreach (TheObject x in list)
xml.Element("MyXMLFile").Add(new XElement("Item",
new XElement("Timestamp", x.Timestamp.Ticks),
new XElement("Number1", x.Number1),
new XElement("Number2", x.Number2),
new XElement("String1", x.String1),
new XElement("String2", x.String2)));
xml.Save("my_file.xml");
}
static void LoadFromXml(ref List<TheObject> list)
{
XDocument xml = XDocument.Load("my_file.xml");
// and here it is... convert xml document into list in one line...
list = (from x in xml.Descendants("Item")
select new TheObject
{
Timestamp = new DateTime(long.Parse(x.Element("Timestamp").Value)),
Number1 = int.Parse(x.Element("Number1").Value),
Number2 = decimal.Parse(x.Element("Number2").Value),
String1 = x.Element("String1").Value,
String2 = x.Element("String2").Value
}).ToList<TheObject>();
// pretty cool, huh :-)
}
}
}
Hope this helps.