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