Saturday, August 11, 2012

Customizing the XML root node using Linq

Sometimes we come across a situation where the XML data, our application received from different sources needs to be having the Root node as expected by our application.

Obviously the restriction can be applied on other application for defining the XML as expected by the calling application. But is the datasource are dynamic then it can create some issues.

In today's example we will see a simple way to customize XML root node using the LINQ as per our requirement. 

For this example to work System.Xml.Linq namespace should be referenced.


<?xml version="1.0" encoding="utf-8" ?>
    <name>Aryan Mehta</name>
    <name>Steve Martin</name>
    <name>Sandra Smith</name>
    <city>New York</city>
    <country>United States</country>

//Loading the customers xml into the XElement object
XElement oXElement = XElement.Load(AppDomain.CurrentDomain.BaseDirectory + "Customers.xml");

//select all the elements using Linq 
var AllElements = from p in oXElement.Elements() select p;

//Defining oXElementReturn to hold the customized xml
XElement oXElementReturn = null;

//Adding customized root node to the return XElement
oXElementReturn = new XElement("CustomizedRootNode");

//Looping through all the elements in the xElement
foreach (XElement xElement1 in AllElements)
   //Creating a customized parent node inside root node
   XElement oXElementNode = new XElement("CustomizedParentNode");

   //Looping through all the elements inside parent node
   foreach (XElement xElement2 in xElement1.Descendants())
     //Adding the node name and values to the parent node
     XElement oNewXElement = new 
     oNewXElement.Value = xElement2.Value;
   //Finally the parent node is added to the root node
//Once the customized return xElement is ready, the output can be displayed on console window


As it can be seen the xml document is customized as per my needs. I am not saying this is the perfect way but this is one of the way you can use to customize the Xml Root node and Parent Node.

And this can be extended to modify the Xml elements also as per your requirement.

I have used Console.Write for writing the output to demonstrate the output retrieved. You can use any way the data is required to be displayed or stored in a collection.

Happy Coding.........

No comments :

Post a Comment