| 描述:利用XmlTextWriter类来格式化XML非常简单地达到使XML数据地可读性增强。
             
             XML许多优点中一个非常主要地优点就是:它能够被人类和计算机方便地读取。XML开发人员可以用任何文本编辑器打开或编辑XML数据。尽管计算机可以轻松读取没有缩进和格式化地XML文档,但对人类来说,看起来就有点费劲了。比如下面地文档:<websites>
            <website><url>http://xml.luohuedu.net/
            </url>
            <title>【孟宪会之精彩世界】之
            XML开发者园地</title>
            <desc>讨论XML技术和Web技术地专业站点。</desc></website>
            <website><url>http://lucky_elove.www1.dotnetplay
            ground.com/</url>
            <title>【孟宪会之精彩世界】之.NET开发者园地</title>
            <desc>讨论.NET技术和应用的专业站点。</desc>
            </website>
            </websites> 为了增强可读性,我们可以使用.NET框架下的XmlTextWriter类轻松实现。 使用XmlTextWriter类的Formatting和Indentation属性可以方便地实现格式的缩进和层次关系,只需要使用Formatting.Indented和Indentation属性,如果Indentation属性没有设置值,则默认是2个空格位置的缩进。也可以使用IndentChar属性来用其它的字符填充缩进的位置。下面就是利用XmlTextWriter把数据装载进XmlDocument的DOM对象,然后用XmlDocument类的WrriteTo()方法直接把数据写进XmlTextWriter中。            
             C#代码:string filePath ="c:\\TestFormat.xml";
            XmlTextWriter writer = new XmlTextWriter(filePath,Encoding.UTF8);
            writer.Formatting = Formatting.Indented;
            writer.Indentation = 4;
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(@"<websites>
            <website><url>http://xml.luohuedu.net/
            </url>
            <title>【孟宪会之精彩世界】之
            XML开发者园地</title>
            <desc>讨论XML技术和Web技术地专业站点。</desc></website>
            <website><url>http://lucky_elove.www1.dotnetplay
            ground.com/</url>
            <title>【孟宪会之精彩世界】之.NET开发者园地</title>
            <desc>讨论.NET技术和应用的专业站点。</desc>
            </website>
            </websites>");
            doc.WriteTo(writer);
            writer.Close(); 下面就是输出的结果:<websites>
            <website>
            <url>http://xml.luohuedu.net/</url>
            <title>【孟宪会之精彩世界】之XML开发者园地</title>
            <desc>讨论XML技术和Web技术地专业站点。</desc>
            </website>
            <website>
            <url>http://lucky_elove.www1.dotnetplayground.com/</url>
            <title>【孟宪会之精彩世界】之.NET开发者园地</title>
            <desc>讨论.NET技术和应用的专业站点。</desc>
            </website>
            </websites> 哈哈,看,多整齐啊:)~! |