Wednesday, June 6, 2012

LINQ to XML Add new Elements


In this post LINQ to XML Add new Elements, we shall see how to add new elements to an existing XML structure. We will load an XML file from the disk, add a new element to the existing collection and save the updated XML to the disk.

Assume that we have the following XML fragment

   <Employees>
 <Employee>
<Name>
<FirstName>Henry</FirstName>
<LastName>Ford</LastName>
  </Name>
<Age>65</Age>
<Department Name="Automobile" />
  </Employee>
  <Employee>
<Name>
<FirstName>Bill</FirstName>
<LastName>Gates</LastName>
</Name>
<Age>55</Age>
<
Department Name="Software" />
  </Employee>
  </Employees>

   Now we will add a new Employee tag to the XML file and save the changes.

XElement xEmp = XElement.Load(@"D:\Employees.xml");
//
xEmp.Add(
    new XElement("Employee",
        new XElement("Name",
            new XElement("FirstName", "Steve"),
            new XElement("LastName", "Jobs")
        ),
        new XElement("Age", "75"),
        new XElement("Department", new XAttribute("Name","Mobile"))
    )
);
//
  xEmp.Save(@"D:\Employees.xml");

   When this code is executed, the Employees.xml file will contain the following tags.
  
  <Employees>
 <Employee>
<Name>
<FirstName>Henry</FirstName>
<LastName>Ford</LastName>
  </Name>
<Age>65</Age>
<Department Name="Automobile" />
  </Employee>
  <Employee>
<Name>
<FirstName>Bill</FirstName>
<LastName>Gates</LastName>
</Name>
<Age>55</Age>
<
Department Name="Software" />
  </Employee>
  <Employee>
<Name>
<FirstName>Steve</FirstName>
<LastName>Jobs</LastName>
</Name>
<Age>75</Age>
<
Department Name="Mobile" />
  </Employee>
  </Employees>


Search Flipkart Products:
Flipkart.com

No comments: