Home > DeveloperSection > Articles > How to create XML file through C Sharp

How to create XML file through C Sharp


XML XML 
Ratings:
0 Comment(s)
 5262  View(s)
Rate this:

How to create XML file through C#.Net

Here I’m creating XML file through C#.

try

            {

                string filename = "c:\\firstXML.xml";

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

                XmlDocument xmlDoc = new XmlDocument();

//creating new XML document

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

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

                xmlWriter.Formatting = Formatting.Indented;

//setting XmlWriter formating to be indented

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

//writing version and encoding type of XML in file.

                xmlWriter.WriteStartElement("Employee");

//writing first element

                xmlWriter.Close();

//closing writer

 

                xmlDoc.Load(filename);

//loading XML file

 

                XmlNode root = xmlDoc.DocumentElement;

//creating child nodes.

                XmlElement childNode1 = xmlDoc.CreateElement("ID");

                XmlElement childNode2 = xmlDoc.CreateElement("Name");

                XmlElement childNode3 = xmlDoc.CreateElement("Address");

 

//adding child node to root.

                root.AppendChild(childNode1);

                childNode1.InnerText = "1";

//writing inner text of child node

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

            }

Screen Shot


Don't want to miss updates? Please click the below button!

Follow MindStick