XmlTextWriter writer = new XmlTextWriter("example.xml", null); writer.WriteStartElement("book"); writer.WriteStartElement("title"); writer.WriteString("The Catcher in the Rye"); writer.WriteEndElement(); // end title writer.WriteStartElement("author"); writer.WriteString("J.D. Salinger"); writer.WriteEndElement(); // end author writer.WriteEndElement(); // end book writer.Close();
XmlDocument doc = new XmlDocument(); XmlElement root = doc.CreateElement("root"); doc.AppendChild(root); XmlElement child1 = doc.CreateElement("child1"); root.AppendChild(child1); XmlElement child2 = doc.CreateElement("child2"); root.AppendChild(child2); XmlElement child3 = doc.CreateElement("child3"); root.AppendChild(child3); root.LastChild.WriteEndElement(); doc.Save("example.xml");This code creates an XML document programmatically and uses the WriteEndElement method to close the last element added to the root element. The resulting XML file contains three child elements and an end tag for the root element.