XmlTextWriter类可以把XML写入一个流、文件或TextWriter对象中。
简单例子:
private void button2_Click(object sender, System.EventArgs e)
{
string filename = "booknew.xml";
XmlTextWriter tw = new XmlTextWriter(filename,null);
tw.Formatting = Formatting.Indented;
tw.WriteStartDocument();
tw.WriteStartElement("book");
tw.WriteAttributeString("genre","Mystery");
tw.WriteAttributeString("publicationdate","2001");
tw.WriteAttributeString("ISBN","123456789");
tw.WriteElementString("title","Case of the Missing Cookie");
tw.WriteStartElement("author");
tw.WriteElementString("name","Cookie Monster");
tw.WriteEndElement();
tw.WriteElementString("price","9.99");
tw.WriteEndElement();
tw.WriteEndDocument();
tw.Flush();
tw.Close();
}
代码生成后的xml文档booksnew.xml:
<?xml version="1.0"?>
<book genre="Mystery" publicationdate="2001" ISBN="123456789">
<title>Case of the Missing Cookie</title>
<author>
<name>Cookie Monster</name>
</author>
<price>9.99</price>
</book>
可 以看出,在XML文档中,有一个起始方法和结束方法(WriteStartElement和WriteEndElement),其他专用的写入方 法:WriteCData可以输入一个Cdata;WriteComment以正确的XML格式写入注释。WriteChars写入字符缓冲区的内容。
利用.NET DOM,XmlDocument创建一个文档
private XmlDocument doc= new XmlDocument();
private void button2_Click(object sender, System.EventArgs e)
{
XmlDeclaration newDec = doc.CreateXmlDeclaration("1.0",null,null);
doc.AppendChild(newDec);
XmlElement newRoot = doc.CreateElement("newBookstore");
doc.AppendChild(newRoot);
//创建一个新的book元素
XmlElement newBook = doc.CreateElement("book");
//创建并设置book元素的属性
newBook.SetAttribute("genre","Mystery");
newBook.SetAttribute("publicationdate","2001");
newBook.SetAttribute("ISBN","123456789");
//创建一个title元素
XmlElement newTilte = doc.CreateElement("title");
newTilte.InnerText ="Case of the Missing Cookie";
newBook.AppendChild(newTilte);
//创建author元素
XmlElement newAuthor = doc.CreateElement("author");
newBook.AppendChild(newAuthor);
XmlElement newName = doc.CreateElement("name");
newName.InnerText = "C.Monster";
newAuthor.AppendChild(newName);
newPrice.InnerText = "9.95";
newBook.AppendChild(newPrice);
doc.DocumentElement.AppendChild(newBook);
XmlTextWriter tr = new XmlTextWriter("booksEdit.xml",null);
tr.Formatting = Formatting.Indented;
doc.WriteContentTo(tr);
tr.Close();
}
代码生成后的文档:
<?xml version="1.0"?>
<newBookstore>
<book genre="Mystery" publicationdate="2001" ISBN="123456789">
<title>Case of the Missing Cookie</title>
<author>
<name>C.Monster</name>
</author>
<price>9.95</price>
</book>
</newBookstore>
如 果从头开始创建一个文档,可以使用XmlTextWrite。还可以使用XmlDocument。使用哪个比较好?如果要写入Xml流的数据已经准备好, 最好的选择用XmlTextWriter类,但是如果需要一次建立Xml文档的一小部分,在不同的地方插入节点,用XmlDocument创建文档就比较 好。