使用XmlWriter对象
XmlWriter类可以把XML写入一个流,文件,StringBuilder,TextWriter或另一个XmlWriter对象中。代码:
运行后生成文件booknew.xml:
1
XmlWriterSettings settings = new XmlWriterSettings();
2
//是否缩进
3
settings.Indent = true;
4
//属性是否在新行
5
settings.NewLineOnAttributes = true;
6
XmlWriter writer = XmlWriter.Create("booknew.xml", settings);
7
writer.WriteStartDocument();
8
writer.WriteStartElement("book");
9
writer.WriteAttributeString("genre", "Mystery");
10
writer.WriteAttributeString("publicationdate", "2001");
11
writer.WriteAttributeString("ISBN", "123456789");
12
writer.WriteElementString("title", "Case of the Missing Cookie");
13
writer.WriteStartElement("author");
14
writer.WriteElementString("name", "Cookie Monster");
15
writer.WriteEndElement();
16
writer.WriteElementString("price", "9.99");
17
writer.WriteEndElement();
18
writer.WriteEndDocument();
19
writer.Flush();
20
writer.Close();
XmlWriterSettings settings = new XmlWriterSettings();2
//是否缩进3
settings.Indent = true;4
//属性是否在新行5
settings.NewLineOnAttributes = true;6
XmlWriter writer = XmlWriter.Create("booknew.xml", settings);7
writer.WriteStartDocument();8
writer.WriteStartElement("book");9
writer.WriteAttributeString("genre", "Mystery");10
writer.WriteAttributeString("publicationdate", "2001");11
writer.WriteAttributeString("ISBN", "123456789");12
writer.WriteElementString("title", "Case of the Missing Cookie");13
writer.WriteStartElement("author");14
writer.WriteElementString("name", "Cookie Monster");15
writer.WriteEndElement();16
writer.WriteElementString("price", "9.99");17
writer.WriteEndElement();18
writer.WriteEndDocument();19
writer.Flush();20
writer.Close();运行后生成文件booknew.xml:
1
<?xml version="1.0" encoding="utf-8"?>
2
<book
3
genre="Mystery"
4
publicationdate="2001"
5
ISBN="123456789">
6
<title>Case of the Missing Cookie</title>
7
<author>
8
<name>Cookie Monster</name>
9
</author>
10
<price>9.99</price>
11
</book>
<?xml version="1.0" encoding="utf-8"?>2
<book3
genre="Mystery"4
publicationdate="2001"5
ISBN="123456789">6
<title>Case of the Missing Cookie</title>7
<author>8
<name>Cookie Monster</name>9
</author>10
<price>9.99</price>11
</book>
浙公网安备 33010602011771号