Creating a New Xml Document from Scratch in C#

dotnetlogo
To create a new XmlDocument, start by creating an XmlDocument object. The XmlDocument object contains CreateElement and CreateAttribute methods that are used to add nodes to the XmlDocument object. The XmlElement contains the Attributes property, which is an XmlAttribute-Collection. The XmlAttributeCollection inherits from the XmlNamedNodeMap class, which is a collection of names with corresponding values.
The following code shows how an XmlDocument can be created from scratch and saved to a file:

protected void Button1_Click(object sender, EventArgs e)
{ //Declare and create new XmlDocument XmlDocument xmlDoc = new XmlDocument();
XmlElement el;
int childCounter;
int grandChildCounter;
//Create the xml declaration first
xmlDoc.AppendChild(
xmlDoc.CreateXmlDeclaration(“1.0”, “utf-8”, null));
//Create the root node and append into doc
el = xmlDoc.CreateElement(“myRoot”);
xmlDoc.AppendChild(el);
//Child Loop
for (childCounter = 1; childCounter <= 4; childCounter++)
{
XmlElement childelmt;
XmlAttribute childattr;
//Create child with ID attribute
childelmt = xmlDoc.CreateElement(“myChild”);
childattr = xmlDoc.CreateAttribute(“ID”);
childattr.Value = childCounter.ToString();
childelmt.Attributes.Append(childattr);
//Append element into the root element
el.AppendChild(childelmt);
for (grandChildCounter = 1; grandChildCounter <= 3; grandChildCounter++)
{
//Create grandchildren childelmt.AppendChild(xmlDoc.CreateElement(“GrandChild”));}}
//Save to file
xmlDoc.Save(MapPath(“XmlDocumentTest.xml”));
}

This code started by creating an instance of an XmlDocument. Next, the XML declaration is created and placed inside the child collection. An exception is thrown if this is not the first child of the XmlDocument. The following is the XML file that was produced by running the code sample:

<?xml version="1.0" encoding="utf-8"?>
<myRoot>
<myChild ID="1">
<GrandChild />
<GrandChild />
<GrandChild />
</myChild>
<myChild ID="2">
<GrandChild />
<GrandChild />
<GrandChild />
</myChild>
<myChild ID="3">
<GrandChild />
<GrandChild />
<GrandChild />
</myChild>
<myChild ID="4">
<GrandChild />
<GrandChild /> <GrandChild /> </myChild></myRoot>

kick it on DotNetKicks.com

Anky Goyal

I am MCPD certified in .NET and working on .NET technologies for past 3yrs. I am very passionate about the new features which get introduced in the technology. I am here to share the new features i get to know in the world of Microsoft. Follow me on twitter @ankygoyal [email protected]Ankit Goyal

More Posts - Website