July 22, 2009

Create Xml using XmlDocument in asp.net

In this example, I will create a xml file using the XMLDocument class of the .NET framework. I will take advantage of the XmlElement, XMLAttribute and XmlComment classes.

At first, I will create a web page with a button control. The code for the page is below.

    <form id="form1" runat="server">
        <asp:Button ID="Button1" runat="server" Text="Get Xml" OnClick="GetXml" />

The Button control has a OnClick event handler that will create the xml file. Here is the code for the GetXml() method.

        protected void GetXml(object sender, EventArgs e)
            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", null));//create declaration

            XmlElement el = doc.CreateElement("root");//create root element

            XmlElement child = doc.CreateElement("user");//create child element
            child.InnerText = "user1";                   //add text to element
            XmlAttribute att = doc.CreateAttribute("id");//create attribute
            att.Value = "1";                             //add value to attribute
            child.Attributes.Append(att);                //add attribute to element

            el.AppendChild(child);                       //add child element to root element
            el.AppendChild(doc.CreateComment("comment1"));//add comment

            child = doc.CreateElement("user");
            child.InnerText = "user2";

            att = doc.CreateAttribute("id");
            att.Value = "2";


            doc.Save(Server.MapPath("~/App_Data/GetXml.xml"));// save xml file

The method starts by creating a Xml-declaration using the CreateXmlDeclaration() method. Then, I am adding a root element using the XmlElement class, adding child elements using AppendChild() method and adding attributes using XmlAttributes objects to the elements. Finally, I am saving the file using the save() method of the XmlDocument() object.

Running this page and clicking the button produces the following xml file.

<?xml version="1.0" encoding="utf-8"?>
  <user id="1">user1</user>
  <user id="2">user2</user>


GeminiLibra said...

Any suggestions as to how can we create a web menu user control using the XML. This menu will be referenced in each of the web pages part of the website.

i need to create a menu control using XML. any suggestions?

Reference: Shahed Kazi at AspNetify.com