LINQ to XML (C#) create new xml document

How to create a new xml with LINQ

  1.  
  2. var objCars= new[]
  3. {
  4. new {CarID = 2, CarName = "Ford", Fuel = "Diesel"},
  5. new {CarID = 3, CarName = "Audi", Fuel = "Diesel"},
  6. new {CarID = 4, CarName = "Mercedes", Fuel = "Diesel"},
  7. new {CarID = 1, CarName = "BMW", Fuel = "Diesel"}
  8. };
  9.  
  10. XElement _cars = new XElement("cars",
  11. from c in objCars
  12. select new XElement("car",
  13. new XElement("name", c.CarName),
  14. new XAttribute("ID", c.CarID),
  15. new XElement("Fuel", c.Fuel)
  16. )
  17. );
  18. Console.WriteLine(_cars);
  19.  
  20.  

so this will print something like:

Ford
Diesel

Audi
Diesel

Mercedes
Diesel

BMW
Diesel

1 Response to "LINQ to XML (C#) create new xml document"