XmlTextWriter class
It is obviously not difficult to create an XML document using the methods in this section. For years, developers have created XML documents in a way that caches strings, connects them, and then prints the strings in the cache to a file. But the way to create XML documents in this way is only valid if you guarantee that there are no small errors in the string. NETFramework provides a better way to create XML documents by using XmlWriter.
The XmlWriter class outputs XML data to a stream or file in a forward-only (forward-only) way. More importantly, XmlWriter is designed to ensure that all XML data conforms to the w3cxml1.0 recommendation, and you don't even have to worry about forgetting to write the tag, because XmlWriter will write it for you. XmlWriter is the abstract base class for all XmlWriter. NETFramework only provides a single writer class----XmlTextWriter class.
Let's take a look at the differences between Xmlwriters and the old writers, and the following code holds an array of string types:
StringBuilder sb = new StringBuilder("");
sb.Append("");
foreach(string s in theArray) {
sb.Append("
sb.Append(s);
sb.Append("\"/>");
}
sb.Append("");
The code loops through the elements in the data, writes the label text, and accumulates them into a string. The code guarantees that the output is well-formed and notes the indentation of the new line, and supports namespaces. This approach may not be an error when you create a document structure that is simpler. However, when you want to support processing instructions, namespaces, indents, formatting, and entities, the number of code grows exponentially, and the likelihood of error increases.
The XmlWriter Write method feature corresponds to each possible XML node type, which makes the process of creating XML documents more logical and less reliant on cumbersome markup languages. Figure six illustrates how to connect a string data using the XmlTextWriter class method. The code is concise, with XmlWriter code easier to read and better structured.
Figure 6 Serializing a String Array
void CreateXmlFileUsingWriters(String[] theArray, string filename)
{
// Open the XML writer (用默认的字符集)
XmlTextWriter xmlw = new XmlTextWriter(filename, null);
xmlw.Formatting = Formatting.Indented;
xmlw.WriteStartDocument();
xmlw.WriteStartElement("array");
foreach(string s in theArray)
{
xmlw.WriteStartElement("element");
xmlw.WriteAttributeString("value", s);
xmlw.WriteEndElement();
}
xmlw.WriteEndDocument();
// Close the writer
xmlw.Close();
}