Building XML File in C#

Why?
Though I found a lot of information on how to read a XML file, I wasn't able to find a complete solution for building XML structure and writing it to file system for my project. I hope this tutorial (or code sample) is helpful to some people.

For Whom?
This tutorial is designed for people with basic XML knowledge, to serve as a reference when building a XML file, the idea is very simple. Finding all the classes, methods needed is actually what takes time, thus the tutorial concentrates on C# language.

Different from writing a regular file.
When we open a file to write, there are many options available: override if already exists, append, etc. It surprises me that there is no single class in C# that does the following: "Read following XML file, if the XML file doesn't exist, create new XML file (Correct me if I am wrong)." Either XmlTextWriter or XmlDocument satisfy the requirement, the combination of the two works well.

Code Sample


Sample Output



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;
        }
posted @ 2006-08-18 20:57  y9902  阅读(313)  评论(0编辑  收藏  举报