Before LINQ to XML we were used XMLDocument for manipulations in XML like adding attributes, elements and so on. Now LINQ to XML uses XDocument for the same kind of thing. Syntaxes are much easier than XMLDocument and it requires a minimal amount of code.
The code below will load the XML file into the XMLDocument or XDocument. It creates the new attribute and sets the value to that attribute. It creates the new element and adds the newly created attributes to that element. Finally the new element will be added to the loaded XML file.
Here is the code to manipulate XML using XMLDocument as well as XDocument.
Manipulation Using XMLDocument
public void XMLDocumentManipulation()
{
//Loading the XML file in the XMLDocument
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Test.XML");
//Get the FirstChild from the XMLDocument
XmlNode conStringNode = xmlDoc.FirstChild;
//Creating a new attribute called Name
XmlAttribute nameAttribute = xmlDoc.CreateAttribute("Name");
//Set the value for that attribute
nameAttribute.Value = "TestName";
//Creating a new attribute called Class
XmlAttribute conStrAttribute = xmlDoc.CreateAttribute("Class");
//Set the value for that attribute
conStrAttribute.Value = "TestClass";
//Creating the new Element
XmlElement addElement = xmlDoc.CreateElement("add");
//Adding the above created attributes to that Element
addElement.Attributes.Append(nameAttribute);
addElement.Attributes.Append(conStrAttribute);
//Appending the new element to the firstchild of the XMLDocument
conStringNode.AppendChild(addElement);
//Saving the changes back to the file
xmlDoc.Save("Test.xml");
}
Manipulation Using XDocument
public void XDocumentManipulation()
{
//Loading the XML file in the XDocument
XDocument XDoc = XDocument.Load("Test.xml");
//Creating a new attribute and setting the values
XAttribute nameAttribute = new XAttribute("Name", "TestName");
XAttribute connStrAttribute = new XAttribute("Class", "TestClass");
//Adding the above attributes to the new Element
XElement newXElement = new XElement("add", nameAttribute, connStrAttribute);
//Adding the new element to the root element of the Xdocument
XDoc.Element("Root").Add(newXElement);
//Saving the changes back to the file
XDoc.Save("Test.xml");
}
From the above two functions, you can see the differences between the XMLDocument and the XDocument. XDocument is very simple to manipulate the XML and also the code readability is clear here.