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></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; } |
相关文章: