using System.Xml; void WriteXML() { try { //pick whatever filename with .xml extension string filename = "XML"+DateTime.Now.Day + ".xml"; XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.Load(filename); } catch(System.IO.FileNotFoundException) { //if file is not found, create a new xml file XmlTextWriter xmlWriter = new XmlTextWriter(filename, System.Text.Encoding.UTF8); xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); xmlWriter.WriteStartElement("Root"); //If WriteProcessingInstruction is used as above, //Do not use WriteEndElement() here //xmlWriter.WriteEndElement(); //it will cause the <Root> to be <Root /> xmlWriter.Close(); xmlDoc.Load(filename); } XmlNode root = xmlDoc.DocumentElement; XmlElement childNode = xmlDoc.CreateElement("childNode"); XmlElement childNode2 = xmlDoc.CreateElement("SecondChildNode"); XmlText textNode = xmlDoc.CreateTextNode("hello"); textNode.Value = "hello, world"; root.AppendChild(childNode); childNode.AppendChild(childNode2); childNode2.SetAttribute("Name", "Value"); childNode2.AppendChild(textNode); textNode.Value = "replacing hello world"; xmlDoc.Save(filename); } catch(Exception ex) { WriteError(ex.ToString()); } } void WriteError(string str) { outputBox.Text = str; }
Carsten Siemens edited Revision 3. Comment: Pirated Content - see my comment
XAML guy edited Revision 2. Comment: format
XAML guy edited Revision 1. Comment: added original source link, do you have permission for this?
NOTE: This article was reported as Pirated/Plagiarized Content (content you didn't write) and will be removed. Please do not steal content from others. If you feel we are mistaken, please leave a comment or email tnwiki at Microsoft with a link to this article and with clear and detailed reasons why you own the content or have explicit permission from the author.
Content was taken from: "Reading and Writing XML files using C# .NET"
Published on April 10, 2007
www.codekicks.com/.../reading-and-writing-xml-files-using-c.html