Modify an XML Element using LINQ

Madhu.B.Rokkam
Posted by Madhu.B.Rokkam under C# category on | Points: 40 | Views : 1105
In this we will try to update an xml element

public static void Main()
{
string serializedXml = "<Root><Students><Student>1</Student><Name>Old Name</Name><Age>33</Age></Students></Root>";

XDocument xmlDoc = XDocument.Parse(serializedXml);
var items = from item in xmlDoc.Descendants("Students")
where (item.Element("Student").Value == "1")
select item;


foreach (XElement itemElement in items)
{
itemElement.SetElementValue("Name", "New Name");
}

Console.WriteLine(xmlDoc);
Console.Read();
}


Output

<Root>
<Students>
<Student>1</Student>
<Name>New Name </Name>
<Age>33</Age>
</Students>
</Root>

Comments or Responses

Login to post response