Friday, November 6, 2009

Creating XML File on Visual Studio 2010

Hello Guys,

This code snippet will show you on how to create a simple xml file in Visual Studio 10 Beta 2.

Step 1: Add a namespace to your code behind System.Xml and System.Text

Step 2: In your event/method to create an xml file

//Create a path were to save the xml file
String path = Server.MapPath(@”FolderName\MyFileName.xml”);

//Instantiate an XmlWriterSettings
var xmlWrite = new XmlWriterSettings();

//And other Declaration
xmlWrite.Indent = true;
xmlWrite.OmitXmlDeclaration = true;
xmlWrite.Encoding = Encoding.ASCII;

//Then try to write a data in xml file
Using (var write = XmlWriter.Create(path,xmlWrite))
{
write.WriteComment(“This is a basic sample on how to create xml file”);
write.WriteStartElement(“Head”);
write.WriteStartElement(“Header”);
write.WriteStartAttribute(“Header”);
write.WriteValue(HeaderValue);
write.WriteEndAttribute();
write.WriteEndElement();
write.WriteStartElement(“Footer”);
write.WriteStartAttribute(“Footer”);
write.WriteValue(FooterValue);
write.WriteEndAttribute();
write.WriteEndElement();
write.Flush();
}

That’s it. This sample created on asp.net project.

No comments: