使用XmlWriter写XML文件





private const string filename = "demo.xml"; static void Main(string[] args) { XmlTextWriter writer=new XmlTextWriter(filename,null); //进行输出格式缩进设置 writer.Formatting = Formatting.Indented; //写XML声明 writer.WriteStartDocument(); //写出<?name text>的形式 string PItext = "type='text/xsl' href='book.xsl'"; writer.WriteProcessingInstruction("xml-stylesheet", PItext); //写DOCTYPE声明 writer.WriteDocType("book", null, null, "<!ENTITY h 'hardcover'>"); //写注释 writer.WriteComment("这是xml注释行"); //写一个开始元素(根元素) writer.WriteStartElement("book"); //属性 writer.WriteAttributeString("genre","novel"); writer.WriteAttributeString("ISBN","1-234-4546"); //书名元素 writer.WriteElementString("title","XML大全"); ////Write the style element writer.WriteStartElement("style"); writer.WriteEntityRef("h"); writer.WriteEndElement(); writer.WriteElementString("price","23"); //写入CDATA writer.WriteCData("Prices 15% off!!!"); //关闭根元素 writer.WriteEndElement(); //结束编写 writer.WriteEndDocument(); //缓冲区的内容写入文件 writer.Flush(); writer.Close(); //声明XML文档并加载 XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.Load(filename); //将XML内容显示在控制台 Console.Write(doc.InnerXml); Console.In.Read();

  

posted @ 2012-09-10 18:50  yxyht  阅读(516)  评论(0编辑  收藏  举报