.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> LINQ >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Create XML document programaticly using LINQ

Posted By:Abhisek Panda       Posted Date: November 30, 2009    Points: 10    Category: LINQ    URL: http://www.dotnetspark.com  
 


       The following console application will create an XML document programmaticly using different LINQ elements,

using System;
using System.Collections.Generic;
using System.Text;
using System.Query;
using System.Xml.XLinq;
using System.Data.DLinq;
using System.Xml;

namespace XLinqBasics
{
    class Car
    {
        public string OwnerName;
        public int ID;
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Create XML document Programatically\n");

            // CreateFunctionalXmlElement();
            // CreateFunctionalXmlDoc();
            // LoadExistingXml();
            CreateXmlDocFromArray();
        }

        private static void CreateXmlDocFromArray()
        {
            // Create an anonymous array of types.
            var data = new [] {
                new Car { OwnerName = "Abhisek", ID = 10 },
                new Car { OwnerName = "Satish", ID = 11 },
                new Car { OwnerName = "Mukesh", ID = 12 },
               new Car { OwnerName = "Ranjan", ID = 13 }
            };

            // Now enumerate over the array to build an XElement.
            XElement vehicals =
                new XElement("Inventory",
                    from c in data
                    select new XElement("Car",
                        new XAttribute("ID", c.ID),
                        new XElement("OwnerName", c.OwnerName)
                    )
                );
            Console.WriteLine(vehicals);
        }
        
        private static void LoadExistingXml()
        {
            // Build an XElement from string.
            string myElement =
            @"
              Yellow
              Yugo    
           
";
            XElement newElement = XElement.Parse(myElement);
            Console.WriteLine(newElement);
            Console.WriteLine();

            // Load the SimpleInventory.xml file.
            XDocument myDoc = XDocument.Load("SimpleInventory.xml");
            Console.WriteLine(myDoc);
        }
        
        private static void CreateFunctionalXmlDoc()
        {
            XDocument inventoryDoc =
                new XDocument(
                    new XDeclaration("1.0", "utf-8", "yes"),
                   new XComment("Current Inventory of Cars"),
                        new XElement("Inventory",
                            new XElement("Car", new XAttribute("ID", "1"),
                                new XElement("Color", "Green"),
                                new XElement("Make", "Honda"),
                                new XElement("OwnerName", "Abhisek")
                            ),
                            new XElement("Car", new XAttribute("ID", "2"),
                                new XElement("Color", "Pink"),
                                new XElement("Make", "Tata"),
                                new XElement("OwnerName", "Satish")
                            )
                        )
                    );
            // Display the document.
            Console.WriteLine(inventoryDoc);
            inventoryDoc.Save("SimpleInventory.xml");
        }
       
        private static void CreateFunctionalXmlElement()
        {
            // A 'functional' approach to build an XML document in memory.
            XElement inventory =
                new XElement("Inventory",
                   new XElement("Car", new XAttribute("ID", "1"),
                        new XElement("Color", "Green"),
                       new XElement("Make", "Honda"),
                        new XElement("OwnerName", "Abhisek")
                    )
                );
            // Call ToString() on our XElement.
            Console.WriteLine(inventory);
        }
        
    }
}

           LINQ to XML allow us to build a document in memory. This reduce the amount of required code and also the programming model maps almost directly to the format of well formed XML data. To illustrate we are using a method named CreateFunctionalXMLElement() as follows,

 
private static void CreateFunctionalXmlDoc()
        {
            XDocument inventoryDoc =
                new XDocument(
                    new XDeclaration("1.0", "utf-8", "yes"),
                   new XComment("Current Inventory of Cars"),
                        new XElement("Inventory",
                            new XElement("Car", new XAttribute("ID", "1"),
                                new XElement("Color", "Green"),
                                new XElement("Make", "Honda"),
                                new XElement("OwnerName", "Abhisek")
                            ),
                            new XElement("Car", new XAttribute("ID", "2"),
                                new XElement("Color", "Pink"),
                                new XElement("Make", "Tata"),
                                new XElement("OwnerName", "Satish")
                            )
                        )
                    );
            // Display the document.
            Console.WriteLine(inventoryDoc);
            inventoryDoc.Save("SimpleInventory.xml");
        }
      
         Here the constructor of XElement object is a tree of additional XElements and XAttributes. To create an entire XML document in memory we load the object tree into the constructor of an XDocument type. It will create an in memory document which is also saved in memory.

         The XElement and XDocument type define a constructor that takes XName as the first parameter and a array of objects as second. The parameter, array of objects can consists of any number of traditional LINQ to XML types, as well as simple strings or an object implementing IEnumerable.

         We have created a simple car class that defines a public field for the ID(an int) and public field for a OwnerName(an string). We can create an array of these objects  and build a LINQ query that will select each name to dynamically build a new XElement.
   
 private static void CreateXmlDocFromArray()
        {
            // Create an anonymous array of types.
            var data = new [] {
                new Car { OwnerName = "Abhisek", ID = 10 },
                new Car { OwnerName = "Satish", ID = 11 },
                new Car { OwnerName = "Mukesh", ID = 12 },
               new Car { OwnerName = "Ranjan", ID = 13 }
            };

            // Now enumerate over the array to build an XElement.
            XElement vehicals =
                new XElement("Inventory",
                    from c in data
                    select new XElement("Car",
                        new XAttribute("ID", c.ID),
                        new XElement("OwnerName", c.OwnerName)
                    )
                );
            Console.WriteLine(vehicals);
        }
     
         The XElement and XDocument both support Load() and Parse() methods, which allows us to create an XML object model from string data or external files. See how the two approaches work,

 
  private static void LoadExistingXml()
        {
            // Build an XElement from string.
            string myElement =
            @"
              Yellow
              Yugo    
           
";
            XElement newElement = XElement.Parse(myElement);
            Console.WriteLine(newElement);
            Console.WriteLine();

            // Load the SimpleInventory.xml file.
            XDocument myDoc = XDocument.Load("SimpleInventory.xml");
            Console.WriteLine(myDoc);
        }
        Build the application and it will display the XML document in the console window. This is a simple document which shows how to create, load, save and parse XML documents using LINQ query. You can also work with the existing XML document using LINQ to XML. You can select some portion of XML document, search for perticular data, etc. in using LINQ to XML.



     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend