XmlDocument doc = new XmlDocument(); // create new XML document XmlElement root = doc.CreateElement("root"); // create new root element doc.AppendChild(root); // append root element to the document
XmlElement book = doc.CreateElement("book"); // create new book element XmlAttribute author = doc.CreateAttribute("author"); // create new author attribute author.Value = "J.K. Rowling"; // set author attribute value book.Attributes.Append(author); // add author attribute to the book element XmlElement title = doc.CreateElement("title"); // create new title element title.InnerText = "Harry Potter and the Sorcerer's Stone"; // set title element text book.AppendChild(title); // add title element to the book element root.AppendChild(book); // add book element to the root elementIn this example, we use CreateElement to create a new book element and two child elements (author and title) for the book. We also use CreateAttribute to create a new author attribute for the book, set its value, and append it to the book element. Finally, we append all of the new elements to the XML document starting with the root element. Package/Library Name: System.Xml.