XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("example.xml"); // load an existing XML file XmlElement newElement = xmlDoc.CreateElement("newNode"); // create a new element newElement.InnerText = "Hello World!"; // set its value XmlNode parentNode = xmlDoc.SelectSingleNode("/root"); // select the parent node parentNode.AppendChild(newElement); // add the new element as a child of the parent xmlDoc.Save("example.xml"); // save the modified XML file
XDocument xDoc = new XDocument( new XElement("root", new XElement("child1", "Hello"), new XElement("child2", "World") ) ); xDoc.Root.Add(new XElement("child3", "Foo")); // add a new element to the root node Console.WriteLine(xDoc.ToString()); // output the modified XML documentThis example uses LINQ to XML to create a new XML document with a root element and two child elements. It then adds a third child element to the root element using the Add method of the XContainer class. The modified document is then output to the console. Package library: System.Xml.Linq Both of these examples demonstrate how the AddElement method can be used to add new elements to an XML document. The first example uses the XmlDocument class and the second example uses the XDocument class in the System.Xml and System.Xml.Linq packages, respectively.