Create an XML file by using LINQ

The XML file is widely used in our development, it is very handy when our application needs to communicate with other application or service. LINQ syntax can be used to create an XML file in our practice.


Background

Data Source

Based on the above data, we have a Car class in our code.

public class Car
     {
         public int Year { get; set; }
         public string Manufacturer { get; set; }
         public string Name { get; set; }
         public double Displacement { get; set; }
         public int Cylinders { get; set; }
         public int City { get; set; }
         public int Highway { get; set; }
         public int Combined { get; set; }
}

In order to process the raw data in to Car objects, we need to implement a processing method and an extension method.

private static List ProcessCars(string path)
         {
             var query = File.ReadAllLines(path)            
                             .Skip(1)                 
                             .Where(l => l.Length > 1)    
                             .ToCar();         
             return query.ToList();     
         }

Extension Method

public static class CarExtensions
     {
         public static IEnumerable ToCar(this IEnumerable source)
         {
             foreach(var line in source)
             {
                 var columns = line.Split(',');
                 yield return new Car
                 {
                     Year = int.Parse(columns[0]),
                     Manufacturer = columns[1],
                     Name = columns[2],
                     Displacement = double.Parse(columns[3]),
                     Cylinders = int.Parse(columns[4]),
                     City = int.Parse(columns[5]),
                     Highway = int.Parse(columns[6]),
                     Combined = int.Parse(columns[7])
                 };
             }
         }
     }

Create an XML

private static void CreatXML()
   {
      var records = ProcessCars("fuel.csv");
      var document = new XDocument();         
      var cars = new XElement("Cars",             
                      from record in records              
                      select new XElement("Car",              
                             new XAttribute("Name", record.Name),                        
                             new XAttribute("Combine", record.Combined),                        
                             new XAttribute("Manufacturer", record.Manufacturer))             
                              );         
      document.Add(cars);         
      document.Save("fuel.xml");     
}

As we can see, we create an XML file by using the LINQ syntax. The hierarchy of implementation is demonstrated in the following diagram.

Run the Program

class Program
     {
         static void Main(string[] args)
         {
             CreatXML();
         }
}

We should be able to create an XML file if the program runs successfully. We can locate the XML file in our bin folder of the project solution.

The content of the file


Query the File

We can query an XML file by using LINQ syntax, too. Here is the code.

private static void QueryXML()
         {
             var document = XDocument.Load("fuel.xml");
             var query =
                        from element in document.Element("Cars").Elements("Car")
                        where element.Attribute("Manufacturer").Value == "BMW"
                        select element.Attribute("Name").Value;
             foreach(var name in query)         
             {             
                 Console.WriteLine(name);         
             }     
         }

As we can see, we dive into the element or attribute hierarchically, then we project each selected items.

Run the Program

class Program
     {
         static void Main(string[] args)
         {
             CreatXML();
             QueryXML();
         }
}

Output


1 Reply to “Create an XML file by using LINQ”

Leave a Reply

Your email address will not be published. Required fields are marked *