Friday, October 21, 2011

Adding new nodes into XML document using LINQ

Today example using LINQ with xml, will be used to show example to add new elements in the XML document and to update the existing values of the element nodes.

Using the .Net earlier classes XmlDocument, XmlTextReader,XPathNavigator etc, bulky code was required to traverse through the XML nodes and finding out the node we wanted to modify. But with the help of LINQ, traversing through the XML document is really easy.

Basic definitions:-

a) XDocument class - Represents an XML document.
b) XElement class- Represents an XML element.
c) XDocument.Load method - Creates a new XDocument from a file specified by a URI, 
    from an TextReader, or from an XmlReader.

Lets start the example to see how modifying and addition of nodes can be achieved with the help of LINQ.

Step 1:-

From my previous example i have copied here the same XML document customer.xml file, which contains the details about the customer. Ex:- Name, CompanyName, JobTitle etc.

<?xml version="1.0" encoding="utf-8" ?>
  <Customer Id="1">
    <Name>B. K. Mishra</Name>
    <CompanyName>FIC Limited</CompanyName>
    <JobTitle>Sales Representative</JobTitle>
    <Address>1st Block, 19th cross,sector 7</Address>
  <Customer Id="2">
    <Name>A. K. Mitra</Name>
    <CompanyName>Sourcesoft Ltd</CompanyName>
    <JobTitle>Maketing Manager</JobTitle>
    <Address>Building no-10, second floor,1st block</Address>
  <Customer Id="3">
    <Name>S. Reddy</Name>
    <CompanyName>Edge solution</CompanyName>
    <JobTitle>Sales Representative</JobTitle>
    <Address>Raheja arcade,3rd floor, sector 1</Address>
  <Customer Id="4">
    <Name>K. Manakotte</Name>
    <CompanyName>Info Ltd</CompanyName>
    <JobTitle>Marketing Manager</JobTitle>
    <Address>Citi tower, MG Road</Address>

Step 2:-

Now i will be writing the code in code behind file to load the xml document and then to add element to the existing xml tree.

XDocument xDoc = XDocument.Load("Customers.xml");
//retrieving the maximum value of Id attribute from the customer node 
var maxID = (from p in xDoc.Descendants("Customer")
                        select p.Attribute("Id").Value).Max();

//incrementing the ID value by 1
int newID = Convert.ToInt16(maxID)+1;

//creating a new customer element with Id attribute having newly created Id value
// then creating all the child elementes with respected value to each node
XElement xeCustomer = new XElement("Customer"new XAttribute("Id", newID + 1), 
                                                                   new XElement("Name""Stephen Smith"),
                                                                   new XElement("CompanyName""Nous System"),
                                                                   new XElement("JobTitle""Marketing Manager"), 
                                                                   new XElement("Address""Sky arcade,Karol Bagh"), 
                                                                   new XElement("City""Delhi"),
                                                                   new XElement("Country""India"), 
                                                                   new XElement("Fax""011-23455555"), 
                                                                   new XElement("EmailId"""));

//adding the newly created XElement to the xDoc object parent xml tree

//Retrieving all the customer details from the xDoc
var customerList = from cust in xDoc.Descendants("Customer")
                                 select new
                                     CustomerName = cust.Element("Name").Value,
                                     JobTitle = cust.Element("JobTitle").Value,
                                     Fax = cust.Element("Fax").Value,
                                     EmailId = cust.Element("EmailId").Value

//displaying the customer details in the 
foreach (var cust in customerList)
    Console.WriteLine(cust.CustomerName + ";" + cust.JobTitle + ";" + cust.Fax + ";" + 


After creation of new elements, the xDoc object can be passed to any database for record creation or can be used to write Xml document into a new file.

I hope this example has served the purpose of giving an idea on how to add new elements into the existing xml document using LINQ.

Happy coding....

No comments :

Post a Comment