JavaScript appears to be disabled. We recommend you enable JavaScript while visiting this site.

(All original content on this site is licensed under the Creative Commons License Attribution-Noncommercial-No Derivative Works 3.0.)

Vehicle gas DTD .NET objects and XML parsing with LINQ

The code contained below is a rough draft, and will eventually be moved into an assembly, and the code posted.

At some point in 2007 I started keeping track of my gas mileage in an XML file, with a custom DTD for validation (and intellisense in oXygen).

I present below the code necessary to create an rough object from the XML, and the LINQ to parse it out.

C# objects

	public class Vehicle {
		public int Id { get; set; }
		public String Make { get; set; }
		public String Model { get; set; }
		public int Year { get; set; }
		public IEnumerable Fillups { get; set; }
	}

	public class Fillup {
		public int Id { get; set; }
		public DateTime Date { get; set; }
		public int MilesTotal { get; set; }
		public Decimal MilesDriven { get; set; }
		public Decimal Gallons { get; set; }
		public Decimal CostPerGallon { get; set; }
		public Decimal CostTotal { get; set; }
		public String Notes { get; set; }
	}

LINQ to XML

XDocument vehicleGasXml = XDocument.Load(@"C:\path\to\vehicle_gas.xml");

IEnumerable vehicles = from vehicle in vehicleGasXml.Descendants("vehicle")
	select new Vehicle {
		Id = int.Parse(vehicle.Attribute("id").Value),
		Make = vehicle.Element("make").Value,
		Model = vehicle.Element("model").Value,
		Year = int.Parse(vehicle.Element("year").Value),
		Fillups = from fillup in vehicle.Descendants("fillup")
			select new Fillup {
			  Id = int.Parse(fillup.Attribute("id").Value),
			  Date = DateTime.ParseExact(fillup.Element("date").Value, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture),
			  MilesTotal = int.Parse(fillup.Element("milesCar").Value),
			  MilesDriven = decimal.Parse(fillup.Element("milesDriven").Value),
			  Gallons = decimal.Parse(fillup.Element("gallons").Value),
			  CostPerGallon = decimal.Parse(fillup.Element("costGallon").Value),
			  CostTotal = decimal.Parse(fillup.Element("costTotal").Value),
			  Notes = fillup.Element("notes").Value
			}
	};

As always, suggestions appreciated. (Although I've already got code that, using .NET 4, creates some rather nice charts with the information contained within a document such as this, and consider this close to complete; name information isn't grabbed, but I'm not sure that's altogether necessary ...)

blog comments powered by Disqus