< Day Day Up > |
13.7 Controlling XmlTextWriter Formatting
TechniqueAn XmlTextWriter object is used in conjunction with the Save method of an XmlDocument object to write XML to a file. After you create an XmlTextWriter object, you control the formatting by changing the Formatting , IndentChar , Indentation , and QuoteChar properties. You use the Formatting property to control indentation. If it is not set to Formatting.Indented , then indentation does not occur when the file is written. If indentation is enabled, you can set the IndentChar property. It allows you to change the default character used for indention. The default value is a space character, but you can change it to any character you desire . Note, however, that any nonwhitespace character causes extra text nodes to be created in the final document, which can cause side effects if you read it in later. You generally want to set this value to the tab character ( '\t' ) or leave the default. Indentation is also coupled with the Formatting property as well as the IndentChar property. Indentation refers to the number of IndentChar characters to insert whenever indentation is output to the final XML file. In other words, if this value is set to 2 and the IndentChar is the space character, then two spaces are inserted for each indentation level. You use the QuoteChar property to set the character used for attribute values. Each attribute value within an XML document must be surrounded by either single or double quotation marks. Changing the QuoteChar property allows you to choose which punctuation symbol to use: XmlTextWriter writer = new XmlTextWriter( filename, NULL ); writer.Formatting = Formatting.Indented; writer.IndentChar = '\t'; writer.Indentation = 2; writer.QuoteChar = '\''; xmlDoc.Save( writer ); writer.Close(); CommentsXmlTextWriter is a class designed to write well- formed XML data to a file or stream. It can be used by the XmlDocument class to save the XML document to a file, but you are also free to use the XmlTextWriter methods themselves . There are, of course, advantages and disadvantages to doing so. First of all, being able to write the XML yourself using this class gives you a little bit of flexibility in APIs to use. In other words, you might prefer the XmlTextWriter methods for XML node creation over the corresponding methods defined in the XmlDocument class. However, this flexibility carries with it the disadvantage of utilizing file I/O, which for large files can be slow. Furthermore, the XML document is not retained in memory, which means that any changes require you to read the file into an XmlDocument object and use the node creation methods in that object anyway. If these disadvantages don't apply to you, then the XmlTextWriter class might be the best match for your application. |
< Day Day Up > |