---
title: "Creating XML File in C#"  
description: "trystringfilename = \"c:\\\\firstXML.xml\"//assigning file name of desiredfile we want to create.XmlDocumentxmlDoc = newXmlDocument//creating new XML do"  
author: "Uttam Misra"  
published: 2010-12-20  
updated: 2014-09-18  
canonical: https://www.mindstick.com/blog/77/creating-xml-file-in-c-sharp  
category: "xml"  
tags: ["xml"]  
reading_time: 1 minute  

---

# Creating XML File in C#

\
try

{

string[filename](https://www.mindstick.com/interview/23463/difference-between-include-filename-and-include-filename) = "c:\\firstXML.xml";

//assigning [file name](https://www.mindstick.com/interview/34109/how-do-you-generate-a-unique-file-name-to-avoid-overwriting-an-existing-one) of desiredfile we want to create.

XmlDocumentxmlDoc = new XmlDocument();

//creating new XML [document](https://www.mindstick.com/articles/328642/what-to-consider-while-choosing-a-software-documentation-tool)

XmlTextWriter xmlWriter= new XmlTextWriter(filename, System.Text.[Encoding](https://www.mindstick.com/interview/752/how-is-encoding-handled-in-ajax).UTF8);

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

xmlWriter.Formatting = Formatting.Indented;

//setting XmlWriter formating tobe indented

xmlWriter.WriteProcessingInstruction("xml", "[version](https://www.mindstick.com/articles/12845/things-to-remember-while-migrating-odoo-to-a-better-version)='1.0'encoding='UTF-8'");

//[writing](https://www.mindstick.com/articles/12997/5-essential-tips-on-resume-writing-for-business-analysts) version and encodingtype of XML in file.

xmlWriter.WriteStartElement("[Employee](https://www.mindstick.com/articles/85431/remote-employee-training-tips-tricks)");

//writing first element

xmlWriter.Close();

//closing writer

xmlDoc.Load(filename);

//[loading](https://yourviews.mindstick.com/view/87829/how-to-improve-web-application-speed-with-lazy-loading) [XML file](https://www.mindstick.com/articles/75/how-to-read-and-write-xml-file-through-c-sharp)

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](https://www.mindstick.com/articles/1824/objective-c-exception-handling) ex)

{

MessageBox.Show(ex.Message);

}

---

Original Source: https://www.mindstick.com/blog/77/creating-xml-file-in-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
