使用XmlWriter创建XML文件
1 using System; 2 3 using System.Collections.Generic; 4 5 using System.Text; 6 7 using System.IO; 8 9 using System.Xml; 10 11 12 13 namespace UseXmlWriter 14 15 { 16 17 class Program 18 19 { 20 21 static void Main(string[] args) 22 23 { 24 25 using (MemoryStream ms = new MemoryStream()) 26 27 { 28 29 XmlWriterSettings settings = new XmlWriterSettings(); 30 31 //要求缩进 32 33 settings.Indent = true; 34 35 //注意如果不设置encoding默认将输出utf-16 36 37 //注意这儿不能直接用Encoding.UTF8如果用Encoding.UTF8将在输出文本的最前面添加4个字节的非xml内容 38 39 settings.Encoding = new UTF8Encoding(false); 40 41 42 43 //设置换行符 44 45 settings.NewLineChars = Environment.NewLine; 46 47 48 49 using (XmlWriter xmlWriter = XmlWriter.Create(ms, settings)) 50 51 { 52 53 54 55 //写xml文件开始<?xml version="1.0" encoding="utf-8" ?> 56 57 xmlWriter.WriteStartDocument(false); 58 59 //写根节点 60 61 xmlWriter.WriteStartElement("root"); 62 63 //写字节点 64 65 xmlWriter.WriteStartElement("cat"); 66 67 //给节点添加属性 68 69 xmlWriter.WriteAttributeString("color", "white"); 70 71 //给节点内部添加文本 72 73 xmlWriter.WriteString("I'm a cat"); 74 75 xmlWriter.WriteEndElement(); 76 77 78 79 80 81 //通过WriteElementString可以添加一个节点同时添加节点内容 82 83 xmlWriter.WriteElementString("pig", "pig is great"); 84 85 86 87 88 89 xmlWriter.WriteStartElement("dog"); 90 91 //写CData 92 93 xmlWriter.WriteCData("<strong>dog is dog</strong>"); 94 95 xmlWriter.WriteEndElement(); 96 97 98 //添加注释 99 xmlWriter.WriteComment("this is an example writed"); 100 101 102 103 xmlWriter.WriteEndElement(); 104 105 xmlWriter.WriteEndDocument(); 106 107 108 109 } 110 111 112 113 //将xml内容输出到控制台中 114 115 string xml = Encoding.UTF8.GetString(ms.ToArray()); 116 117 Console.WriteLine(xml); 118 119 } 120 121 Console.Read(); 122 123 124 125 } 126 127 } 128 129 }