Home computer programming Creating XML File in C#
computer programming

Creating XML File in C#

how to create xml file in c#
we use xml file for client configuration, each client have different configuration, so we need to custom each client for its configuration

this sample, shows us how to create xml file in c#

try{
 XmlDocument doc = new XmlDocument();

 //(1) the xml declaration is recommended, but not mandatory
 XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
 XmlElement root = doc.DocumentElement;
 doc.InsertBefore(xmlDeclaration, root);

 //(2) string.Empty makes cleaner code
 XmlElement element1 = doc.CreateElement(string.Empty, "EstimationClientSetup", string.Empty);
 doc.AppendChild(element1);

 XmlElement element2 = doc.CreateElement(string.Empty, "ClientSQLServerName", string.Empty);
 XmlText texte2 = doc.CreateTextNode(aa.ServerInstance);
 element2.AppendChild(texte2);
 element1.AppendChild(element2);

 XmlElement element3 = doc.CreateElement(string.Empty, "ClientDatabaseName", string.Empty);
 XmlText texte3 = doc.CreateTextNode(aa.DatabaseName);
 element3.AppendChild(texte3);
 element1.AppendChild(element3);

 XmlElement element4 = doc.CreateElement(string.Empty, "UserSQL", string.Empty);
 XmlText texte4 = doc.CreateTextNode(aa.DatabaseUserName);
 element4.AppendChild(texte4);
 element1.AppendChild(element4);

 XmlElement element5 = doc.CreateElement(string.Empty, "PassSQL", string.Empty);
 XmlText texte5 = doc.CreateTextNode(aa.DatabasePassword);
 element5.AppendChild(texte5);
 element1.AppendChild(element5);

 doc.Save("C:\\Estimate\\" + WindowsIdentity.GetCurrent().User.ToString() + ".xml");
 MessageBox.Show("Configuration Saved, please closed the app");
}
catch (Exception Ex){
 MessageBox.Show(Ex.Message);
}

Author

Ronny

Leave a Reply