using System;
using SystemXml;
namespace WriteXML
{
class Class
{
static void Main( string[] args )
{
// 创建XmlTextWriter类的实例对象
XmlTextWriter textWriter = new XmlTextWriter(C:\\myXmFilexml null);
// 开始写过程调用WriteStartDocument方法
textWriterWriteStartDocument();
// 写入说明
textWriterWriteComment(First Comment XmlTextWriter Sample Example);
textWriterWriteComment(myXmlFilexml in root dir);
// 写入一个元素
textWriterWriteStartElement(Name );
textWriterWriteString(Student);
textWriterWriteEndElement();
// 再写入一个元素
textWriterWriteStartElement(Address );
textWriterWriteString(Colony);
textWriterWriteEndElement();
// 写入字符
char [] ch = new char[];
ch[] = a;
ch[] = r;
ch[] = c;
textWriterWriteStartElement(Char);
textWriterWriteChars(ch chLength);
textWriterWriteEndElement();
// 写文档结束调用WriteEndDocument方法
textWriterWriteEndDocument();
// 关闭textWriter
textWriterClose();
}
}
}
五运用XmlDocument类
XmlDocument类的对象代表了一个XML文档它也是一个非常重要的XML类该类包含了LoadLoadXml以及Save等重要的方法其中Load方法可以从一个字符串指定的XML文件或是一个流对象一个TextReader对象一个XmlReader对象导入XML数据LoadXml方法则完成从一个特定的XML文件导入XML数据的功能它的Save方法则将XML数据保存到一个XML文件中或是一个流对象一个TextWriter对象一个XmlWriter对象中
下面的程序中我们用到了XmlDocument类对象的LoadXml方法它从一个XML文档段中读取XML数据并调用其Save方法将数据保存在一个文件中
// 创建一个XmlDocument类的对象
XmlDocument doc = new XmlDocument();
docLoadXml((Tommy Lex));
// 保存到文件中
docSave(C:\\studentxml);
这里我们还可以通过改变Save方法中参数将XML数据显示在控制台中方法如下
docSave(ConsoleOut);
而在下面的程序中我们用到了一个XmlTextReader对象通过它我们读取booksxml文件中的XML数据然后创建一个XmlDocument对象并载入XmlTextReader对象这样XML数据就被读到XmlDocument对象中了最后通过该对象的Save方法将XML数据显示在控制台中
XmlDocument doc = new XmlDocument();
// 创建一个XmlTextReader对象读取XML数据
XmlTextReader reader = new XmlTextReader(c:\\booksxml);
readerRead();
// 载入XmlTextReader类的对象
docLoad(reader);
// 将XML数据显示在控制台中
docSave(ConsoleOut);
六总结
XML技术作为Net的基石其重要性自然不言而喻Net框架包含了五个命名空间和大量的类来支持与XML技术有关的操作其中SystemXml是最重要的一个命名空间其中的XmlReader类和XmlWriter类以及它们的派生类完成了XML文档的读写操作是最基本也是最重要的类XmlDocument类代表了XML文档它能完成与整个XML文档相关的各类操作同时和其相关的XmlDataDocument类也是非常重要的值得读者的深入研究
附录booksxml文件如下
<?xml version=?> <! This file represents a fragment of a book store inventory database >
<bookstore>
<book genre=autobiography publicationdate= ISBN=>
<title>The Autobiography of Benjamin Franklin</title>
<author>
<firstname>Benjamin</firstname>
<lastname>Franklin</lastname>
</author>
<price></price>
</book>
<book genre=novel publicationdate= ISBN=>
<title>The Confidence Man</title>
<author>
<firstname>Herman</firstname>
<lastname>Melville</lastname>
</author>
<price></price>
</book>
<book genre=philosophy publicationdate= ISBN=>
<title>The Gorgias</title>
<author>
<firstname>Sidas</firstname>
<lastname>Plato</lastname>
</author>
<price></price>
</book>
</bookstore>
[] [] []