Mega Code Archive

 
Categories / C# Book / 06 XML
 

0558 XmlDocument creation

The following creates a document using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Linq; using System.Text; using System.IO; class Program { static void Main() { XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateXmlDeclaration("1.0", null, "yes")); XmlAttribute id = doc.CreateAttribute("id"); XmlAttribute status = doc.CreateAttribute("status"); id.Value = "123"; status.Value = "archived"; XmlElement firstname = doc.CreateElement("firstname"); XmlElement lastname = doc.CreateElement("lastname"); firstname.AppendChild(doc.CreateTextNode("Jack")); lastname.AppendChild(doc.CreateTextNode("James")); XmlElement customer = doc.CreateElement("customer"); customer.Attributes.Append(id); customer.Attributes.Append(status); customer.AppendChild(lastname); customer.AppendChild(firstname); doc.AppendChild(customer); Console.WriteLine(doc); } } Here is an example of declaring a namespace with a prefix while creating an element: using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Linq; using System.Text; using System.IO; class Program { static void Main() { XmlDocument doc = new XmlDocument(); XmlElement customer = doc.CreateElement("o", "customer", "http://yourDomain"); } }