Saturday, January 5, 2019

xml- Part 4 Modifying xml document using linq to xml


Part 1 LINQ to XML



Part 4 Modifying xml document using linq to xml


<?xml version="1.0" encoding="utf-8"standalone="yes"?>
<!--Creating an XML Tree using LINQ to XML -->
<Students>
      <Student Id="101">
            <Name>Rosy</Name>
            <Gender>Female</Gender>
            <TotalMarks>1000</TotalMarks>
      </Student>       
      <Student Id="2">
            <Name>Marina</Name>
            <Gender>Female</Gender>
            <TotalMarks>1000</TotalMarks>
      </Student> 
      <Student Id="3">
            <Name>Katrina</Name>
            <Gender>Female</Gender>
            <TotalMarks>1000</TotalMarks>
      </Student>  
</Students>     
     
--Adding new XML elements:

XDocument xmlDocument = xmlDocument.Load(@"C:\Demo\Demo\Data.xml");

xmlDocument.Element("Students").Add(
        new XElement("Student", new XAttribute("Id", 105),
        new XElement("Name","Todd"),
        new XElement("Gender", "Male"),
        new XElement("TotalMarks", "1000")
        ));

xmlDocument.save(@"C:\Demo\Demo\Data.xml");

To add the xml elements as the first element use AddFirst() method

--To add the xml elment in a specific location in the XML Document, use  AddBeforeSelf() or
-----AddAfterSelf()

xmlDocument.Element("Students")
                       .Elements("Student")
                       .Where(x -> x.Attribute("Id").value=="103").FirstOrDefault()
                       .AddBeforeSelf(
                             new XElement("Student", new XAttribute("Id",106),
                             new XElement("Name","Todd"),
                             new XElement("Gender","Male"),
                             new XElement("TotalMarks",1000)
                             ));

--Updating an xml element in the xml document

xmlDocument.Element("Students")
                       .Elements("Student")
                       .Where( x -> x.Attribute("Id").Value == "106").FirstOrDefault()
                       .SetElementValue("totalMarks", 999);

--Updating an xml comment in the xml document:

xmlDocument.Nodes().OfType<xComment>().FirstOrDefault().Value = "Comment Updated";

No comments:

Post a Comment