Updating XML

In this section, we will look at how we can modify an XML file using LINQ. With LINQ, we can modify the XML file by doing the following:

  • Removing existing nodes in the XML file
  • Inserting new nodes in the XML file
  • Changing the content of existing nodes
  • Saving the XML file back once the operation finishes

For the sake of explanation, we will work on the same XML file that we created in the previous section. We will be writing a code that would add a mobile number element for all of the students. We will add this element in the node element of ContactDetails:

XElement rootUpd = XElement.Parse(xml);
foreach (XElement p in rootUpd.Descendants("Student"))
{
XElement contactDetails = p.Element("contactdetails");
contactDetails.Add(new XElement("MobileNumber", "12345678"));
}
rootUpd.Save("testupd.xml");

In the preceding code, we are looping through all Students present in the XML and are then looping through the child element of ChildDetails. In that node, we are adding the element of MobileNumber. Once the code is executed, we will get the following output in the XML file:

<?xml version="1.0" encoding="utf-8"?>
<Students>
<Student Name="Simaranjit" rollNum="1">
<contactdetails>
<emailaddress>[email protected]</emailaddress>
<phoneNumber>0416274824</phoneNumber>
<MobileNumber>12345678</MobileNumber>
</contactdetails>
</Student>
<Student Name="James" rollNum="2">
<contactdetails>
<emailaddress>[email protected]</emailaddress>
<MobileNumber>12345678</MobileNumber>
</contactdetails>
</Student>
</Students>

In the preceding XML, we have added a MobileNumber element in the ContactDetails node of Student

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.218.226