Creating XML File in C#


try

            {

                stringfilename = 'c:\\firstXML.xml';

//assigning file name of desiredfile we want to create.

                XmlDocumentxmlDoc = new XmlDocument();

//creating new XML document

XmlTextWriter xmlWriter= new     XmlTextWriter(filename, System.Text.Encoding.UTF8);

//creating XmlTestWriter, andpassing file name and encoding type as argument

                xmlWriter.Formatting = Formatting.Indented;

//setting XmlWriter formating tobe indented

xmlWriter.WriteProcessingInstruction('xml', 'version='1.0'encoding='UTF-8'');

//writing version and encodingtype of XML in file.

                xmlWriter.WriteStartElement('Employee');

//writing first element

                xmlWriter.Close();

//closing writer

 

                xmlDoc.Load(filename);

//loading XML file

 

                XmlNoderoot = xmlDoc.DocumentElement;

//creating child nodes.

                XmlElementchildNode1 = xmlDoc.CreateElement('ID');

                XmlElementchildNode2 = xmlDoc.CreateElement('Name');

                XmlElementchildNode3 = xmlDoc.CreateElement('Address');

 

//adding child node to root.

                root.AppendChild(childNode1);

                childNode1.InnerText = '1';

//writing inner text of childnode

                root.AppendChild(childNode2);

                childNode2.InnerText = 'Alex';

                root.AppendChild(childNode3);

                childNode3.InnerText = 'USA';

 

                xmlDoc.Save(filename);

//saving xml file

            }

            catch(Exception ex)

            {

                MessageBox.Show(ex.Message);

           }
Last updated:9/18/2014 1:23:53 PM
Uttam Misra

Uttam Misra

More than 18 years of working experience in IT sector. We are here to serve you best.

2 Comments

Kenny Tangnde
Kenny Tangnde

Hi Uttam Misra ,

     this a nice article,if can you provide some  xml language learn then will very good.

thanks!

Leave Comment