10多年建站經(jīng)驗(yàn), 成都網(wǎng)站建設(shè)、網(wǎng)站建設(shè)客戶(hù)的見(jiàn)證與正確選擇。創(chuàng)新互聯(lián)提供完善的營(yíng)銷(xiāo)型網(wǎng)頁(yè)建站明細(xì)報(bào)價(jià)表。后期開(kāi)發(fā)更加便捷高效,我們致力于追求更美、更快、更規(guī)范。> 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 //要求縮進(jìn) 32
33 settings.Indent = true;
34
35 //注意如果不設(shè)置encoding默認(rèn)將輸出utf-16
36
37 //注意這兒不能直接用Encoding.UTF8如果用Encoding.UTF8將在輸出文本的最前面添加4個(gè)字節(jié)的非xml內(nèi)容 38
39 settings.Encoding = new UTF8Encoding(false);
40
41
42
43 //設(shè)置換行符 44
45 settings.NewLineChars = Environment.NewLine;
46
47
48
49 using (XmlWriter xmlWriter = XmlWriter.Create(ms, settings))
50
51 {
52
53
54
55 //寫(xiě)xml文件開(kāi)始 56
57 xmlWriter.WriteStartDocument(false);
58
59 //寫(xiě)根節(jié)點(diǎn) 60
61 xmlWriter.WriteStartElement("root");
62
63 //寫(xiě)字節(jié)點(diǎn) 64
65 xmlWriter.WriteStartElement("cat");
66
67 //給節(jié)點(diǎn)添加屬性 68
69 xmlWriter.WriteAttributeString("color", "white");
70
71 //給節(jié)點(diǎn)內(nèi)部添加文本 72
73 xmlWriter.WriteString("I'm a cat");
74
75 xmlWriter.WriteEndElement();
76
77
78
79
80
81 //通過(guò)WriteElementString可以添加一個(gè)節(jié)點(diǎn)同時(shí)添加節(jié)點(diǎn)內(nèi)容 82
83 xmlWriter.WriteElementString("pig", "pig is great");
84
85
86
87
88
89 xmlWriter.WriteStartElement("dog");
90
91 //寫(xiě)CData 92
93 xmlWriter.WriteCData("dog is dog");
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內(nèi)容輸出到控制臺(tái)中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 }
文章名稱(chēng):使用XmlWriter創(chuàng)建XML文件-創(chuàng)新互聯(lián)
鏈接地址:
http://weahome.cn/article/djcpph.html