Friday, June 5, 2009

Creating XML document runtime in Asp.net C#

Due to the popularity of XML file most of the times we need to create XML file in runtime. In this post i will show you a simple example how we can create XML file programatically. By using this example you can also make XML file dynamically from SQL Server Database table by iterating across the rows. To make the XML on the fly first add System.Xml namespace in your project. Then create a declaration, a root element first and create elements sequentially. The example code is given below:

protected void Page_Load(object sender, EventArgs e)
{
XmlDocument writer = new XmlDocument();
// Create XML declaration
XmlNode declaration = writer.CreateNode(XmlNodeType.XmlDeclaration, null, null);
writer.AppendChild(declaration);

// Make the root element first
XmlElement root = writer.CreateElement("Article");
writer.AppendChild(root);

//Creating the <Asp.net> element
XmlElement aspnet = writer.CreateElement("Asp.net");
root.AppendChild(aspnet);

//Creating attributes of <Asp.net> element
XmlAttribute id = writer.CreateAttribute("Id");
id.Value =
"0001";
aspnet.Attributes.Append(id);

XmlAttribute
title = writer.CreateAttribute("Title");
title.InnerText =
"Bind Dropdown List";
aspnet.Attributes.Append(title);

XmlAttribute
visit = writer.CreateAttribute("Visit");
visit.InnerText =
"985";
aspnet.Attributes.Append(visit);

XmlAttribute
modified = writer.CreateAttribute("Modified");
modified.InnerText =
"Jan 01, 2009";
aspnet.Attributes.Append(modified);

// Now save/write the XML file into server root location
//Server.MapPath(".") is used to find the root path
writer.Save(Server.MapPath(
".") + "//XMLFile.xml");
}
* Don't forget to add the namespace System.Xml

Ok now we found a XMLFile.xml in our application root directory. Click here to view how we can bind this XML file into GridView. So now we can programatically create a XML file & also we can use it in our application.

For permission related issues Click here.

6 comments:

  1. really..this is great programming in simplest way. Thank you very much.

    ReplyDelete
  2. hi...

    this Article is very simple and super..

    ReplyDelete
  3. thnx nice example :)

    ReplyDelete
  4. huh. technology 's copy&paste but it don't create .xml for me. it no error, too. i don't understand.

    ReplyDelete
  5. Above code is working fine. You may cant accommodate correctly. Send your code to my email. I will check & get back to you soon.

    ReplyDelete

Write your Comment: