LINQ to XML : Modifying XML document

LINQ to XML : Modifying XML document

  • Comments 8

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!!!

Leave a Comment
  • Please add 1 and 1 and type the answer here:
  • Post
  • Welcome to the forty-third issue of Community Convergence. The last few weeks have been consumed by the

  • how to connect database ms access from html file ...

    bcoz i want to need save datas in ms access table using html program tags.

    how to save datas using html will u pls send me a example code

    incase i was using any script language in my html code ?

    pls send me a example code for how to connect Ms access from html

  • Hi, Thanks very much.  I am a beginner and found your link off of Charlie.

  • Thanks a lot for this clear and concise article. Helps me a lot :)

  • thank you so much for such a nice post.

    but please tell me one thing, how do i save this xml into a xml file.?

  • @Zain Shaikh,

    root.Save() as per the example.

  • Thanks dude. It's a nice quick reference that helped me a lot!

  • thanks for this, but i want to add a sub_element having an atribute. how can i do that?

Page 1 of 1 (8 items)