articles

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

How to create XML file through C Sharp

Anonymous User8297 01-Aug-2010
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 = newXmlDocument();
//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

How to create XML file through C Sharp



Updated 04-Mar-2020
I am a content writter !

Leave Comment

Comments

Liked By