blog

Home / DeveloperSection / Blogs / Creating XML File in C#

Creating XML File in C#

Uttam Misra6512 20-Dec-2010


try

            {

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

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

                XmlDocumentxmlDoc = newXmlDocument();

//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);

           }

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

Leave Comment

Comments

Liked By