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.

Customer.xml

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

//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 
               XElement(xElement2.Name.ToString());
     oNewXElement.Value = xElement2.Value;
     oXElementNode.Add(oNewXElement);
   }
   //Finally the parent node is added to the root node
   oXElementReturn.Add(oXElementNode);
}
//Once the customized return xElement is ready, the output can be displayed on console window
Console.WriteLine(oXElementReturn.ToString());

Output:- 


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