Generate XML files using XmlTextWriter
Author:Eve Cole
Update Time:2009-07-07 16:19:39
Project compatibility requires the generation of a series of XML files. Here is a summary of the basic methods of generating XML files.
XmlTextWriter w = new XmlTextWriter("C:XML file name.xml", Encoding.Unicode); //Encoding.Unicode is the encoding format for generating XML files. When the time comes, the output will be: <?xml version="1.0" encoding= "utf-16"?>
w.Formatting = Formatting.Indented; // This is more important. This attribute indicates that the content in the xml file is indented according to levels.
//Start generating the content of the file below
w.WriteStartDocument(); //Start writing xml, and at the end there is a matching w.WriteEndDocument();
w.WriteStartElement("SpotList");
w.WriteAttributeString("xmlns:xsi", "http:www.w3.org/2001/XMLSchema-instance"); //Attributes of the SpotList node w.WriteAttributeString("xmlns:xsd", "http:www.w3. org/2001/XMLSchema"); //SpotList node attributes, final effect: <SpotList xmlns:xsi="http:www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http:www.w3.org /2001/XMLSchema">
w.WriteStartElement("Items");
w.WriteElementString("Name", myPoints[j].Name);
w.WriteElementString("Caption", myPoints[j].Caption);
w.WriteElementString("Addr", myPoints[j].Addr);
w.WriteElementString("Phone", myPoints[j].Phone);
w.WriteStartElement("Intro"); //Final effect: <Intro><![CDATA[related content]]></Intro>
w.WriteCData(myPoints[j].Intro);
w.WriteEndElement();
w.WriteEndElement();
w.WriteEndElement();
w.WriteEndDocument();
w.Close(); //Complete output of xml file and close