Tuesday, April 23, 2013

Creating a XML document with Elements and Attributes using LINQ

Today we are going to create a XML document using LINQ. This example is for helping Beginners to understand multiple ways which can be used to achieve the same output.

First step is to create the XDocument object with the XML declaration.

//Initialization of XDeclaration class instance requires passing version, encoding //and standalone status
XDocument oXDocument = new XDocument(new XDeclaration("1.0","utf-16",null));  

//Creating an Element node to add as root node of the XML //Document
XElement RootNode = new XElement("Root");

//Adding the Root node element to the XDocument object

Now we will try different ways to add elements and attributes to the XML document.

1ST way to add elements and attribute into Root Node:-

//declaring XElement type
XElement oXElement;

//creating an object of XElement class
oXElement= new XElement("Name");
oXElement.Value = "Smith Jones";

//Adding attribute to the first xml node element
oXElement.SetAttributeValue("CustomerID", 1001);

//adding the XElement object to XML root node

oXElement = null;

//repeating the above mentioned steps to add Address and EmailID elements
oXElement = new XElement("Address");
oXElement.Value = "19th Street, New York";

oXElement = null;

oXElement = new XElement("EmailID");
oXElement.Value = "Smith.Jones@Gmail.com";

//serializing the formatted xml document to a File
oXDocument.Save("TextDoc.xml", SaveOptions.None);

When opening the saved XML file with Internet Explorer, following xml output can be seen.


2ND way to add elements and attribute into Root Node:-

//Declaring an XElement array list content with attribute added to first element
XElement[] oXElement = {new XElement("Name","Smith Jones",new XAttribute("CustomerID",1001)),
                        new XElement("Address","19th street, New York"),
                        new XElement("EmailID","Smith.Jones@Gmail.com")};    

//Adding the newly created XElement array list content to the root node

//serializing the formatted xml document to a File 

Identical output can be seen while opening the TextDoc.xml file with Internet explorer.


Happy Coding........