Wriju's BLOG

.NET, Cloud and everything

LINQ to XML : Modifying XML document

You have XML document now you want to modify that XML file using LINQ to XML. It is as easy as you generally modify any database column value.


 


Let us create a dummy XML stream,


 


//Create dummy XML to work


var root = new XElement(“parent”,


    from i in new int[] { 1, 2, 3, 4, 5, 6 }


    select new XElement(“child”,


        new XAttribute(“number”, i)));


 


This will create XML like,


<?xml version=1.0 encoding=utf-8?>


<parent>


  <child number=1 />


  <child number=2 />


  <child number=3 />


  <child number=4 />


  <child number=5 />


  <child number=6 />


</parent>


 


Let us play with this XML file,


 


//Get the element (child3)


XElement child3 = root.Descendants(“child”).First(


    el => (int)el.Attribute(“number”) == 3);


 


//Add element before the child3


child3.AddBeforeSelf(new XElement(“child25”));


 


//Add sub-element to the child3


child3.Add(new XElement(“grandchild”));


 


//Add element after the child3


child3.AddAfterSelf(new XElement(“child35”));


 


//Add attribute to the child3


child3.Add(new XAttribute(“attr”, “something”));


 


//Change the existing attribute


child3.SetAttributeValue(“number”, 100);


 


After all these activities you will get the following output,


 


<?xml version=1.0 encoding=utf-8?>


<parent>


  <child number=1 />


  <child number=2 />


  <child25 />


  <child number=100 attr=something>


    <grandchild />


  </child>


  <child35 />


  <child number=4 />


  <child number=5 />


  <child number=6 />


</parent>


 


Highlighted part is the modified portion of your XML. You can also remove an element,


 


child3.Remove();


 


Namoskar!!!