.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 >> Articles >> LINQ >> Post New Resource Bookmark and Share   

 Subscribe to Articles

LINQ to XML

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

LINQ to XML


        As we know XML is required every where, but programming with XML is very tedious and complex if you are not acquainted with a number of XML technologies like XPath, XQuery, DOC, SAX,etc. As XML is also in .NET framework Microsoft has given an assembly dedicated towards XML programming and that is "System.Xml.dll". This assembly contains a number of namespaces and types to various XML programming techniques as well as some .NET specific XML APIs such as XmlReader/XmlWriter models.

         LINQ to XML helps us in XML data processing. Not only we can use LINQ to XML as a medium to obtain subsets of data from an existing XML document via LINQ queries, but also we can use this API to create, copy and parse XML data. As well just as LINQ to SQL can inter operate with ADO.NET types, LINQ to XML can inter operate with many members of the Sytem.Xml.dll assemblies.

N.B:- LINQ to XML is a new official name for the previously termed XLinq. In fact currently the LINQ to XML namespace is System.Xml.XLinq.

System.Xml.XLinq namespace

     
        The core LINQ to XML assembly defines a single namespace, System.Xml.XLinq. Here you will find a manageable set of types that represents various aspects of an XML document. Its elements and their attributes, XML namespaces, XML comments and processing instructions, and so on. The following table shows the different core members of System.Xml.XLinq.

Member                            Meaning
XAttribute                         Represents an XML attribute on a given XML element
XComment                        Represents an XML comment
XDeclaration                     Represents the opening declaration of an XML document.
XDocument                       Represents the whole XML document
XElement                           Represents a given element in the XML document
XName,XNamespace        Provides a simple manner to define and reference XML namespaces.

       To understand the use of the above members just see the following console application. This application will create an XML document programmaticly.

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.


 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

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