Link for all dot net and sql server video tutorial playlists
Link for slides, code samples and text version of the video
In Part 3 of LINQ to XML tutorial we discussed querying xml document using linq to xml. In this video we will discuss
1. Adding new xml elements to the xml document
2. Updating xml elements in the xml document
3. Updating xml comments in the xml document
4. Deleting existing xml elements from the xml document
Inserting or adding new xml elements to the xml document : The following code adds the student element at the end of the xml document.
XDocument xmlDocument = XDocument.Load(@”C:DemoDemoData.xml”);
xmlDocument.Element(“Students”).Add(
new XElement(“Student”, new XAttribute(“Id”, 105),
new XElement(“Name”, “Todd”),
new XElement(“Gender”, “Male”),
new XElement(“TotalMarks”, 980)
));
xmlDocument.Save(@”C:DemoDemoData.xml”);
To add the xml element as the first element use AddFirst() method.
To add the xml element 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”, 980)
));
To disable formatting the XML document use SaveOptions.DisableFormatting
xmlDocument.Save(@”C:DemoDemoData.xml”, SaveOptions.DisableFormatting);
Updating an xml element in the xml document :
The following code updates student (with Id = 106) TotalMarks to 999
XDocument xmlDocument = XDocument.Load(@”C:DemoDemoData.xml”);
xmlDocument.Element(“Students”)
.Elements(“Student”)
.Where(x =] x.Attribute(“Id”).Value == “106”).FirstOrDefault()
.SetElementValue(“TotalMarks”, 999);
xmlDocument.Save(@”C:DemoDemoData.xml”);
OR
XDocument xmlDocument = XDocument.Load(@”C:DemoDemoData.xml”);
xmlDocument.Element(“Students”)
.Elements(“Student”)
.Where(x =] x.Attribute(“Id”).Value == “106”)
.Select(x =] x.Element(“TotalMarks”)).FirstOrDefault().SetValue(999);
xmlDocument.Save(@”C:DemoDemoData.xml”);
Updating an xml comment in the xml document :
XDocument xmlDocument = XDocument.Load(@”C:DemoDemoData.xml”);
xmlDocument.Nodes().OfType[XComment]().FirstOrDefault().Value = “Comment Updated”;
xmlDocument.Save(@”C:DemoDemoData.xml”);
Deleting xml elements from the xml document
XDocument xmlDocument = XDocument.Load(@”C:DemoDemoData.xml”);
xmlDocument.Root.Elements().Where(x =] x.Attribute(“Id”).Value == “106”).Remove();
xmlDocument.Save(@”C:DemoDemoData.xml”);
The following code removes all “Student” elements that are present under root node “Students”
XDocument xmlDocument = XDocument.Load(@”C:DemoDemoData.xml”);
xmlDocument.Root.Elements().Remove();
xmlDocument.Save(@”C:DemoDemoData.xml”);
Deleting xml comments from the xml document
xmlDocument.Nodes().OfType[XComment]().Remove();