去年写过一篇关于C# XML文件操作的两种方式,但是没有给出样例代码,这里再次给出两种操作XML文件的方式,并且包含部分样例代码。
以下两种XML操作方式,不仅只是适合C# 语言进行开发,其实语言也都适用。
原文链接: 点击打开链接 http://blog.csdn.net/weixingstudio/article/details/7026712
1. 解析类型介绍
XML的解析器主要有DOM和SAX两种。
先简要介绍SAX解析器(Simple API for XML),其实解析器就是对XML进行处理的一套API,相当于一个模块。
SAX解析器是基于事件处理的,需要从头到尾把XML文档扫描一遍,在扫描的过程中,每次遇到一个语法结构时,就会调用这个特定语法结构的事件处理程序,向应用程序发送一个事件。
XmlReader的类提供了一种非常迅速、只向前的只读光标来处理XML数据,因为它是一个流模型,所以内存要求不是很高。但是,没有提供DOM模型的导航功能和读写功能。
DOM是文档对象模型解析,构建文档的分层语法结构,在内存中建立DOM树,DOM树的节点以对象的形式来标识,文档解析文成以后,文档的整个DOM树都会放在内存中。
DOM的优点:
1. 当文档的某一部分被多次的访问时,非常方便。
2. 需要对文档进行调整或者一次性的访问整个文档。
3. DOM可以随时的访问文档中的某个部分。
4. 可以避免一些无效的操作。
DOM结构是完全的存储在内存中的,所以如果文档较大的话,会占用大量的内存。
因为XML文档没有大小限制,所以一些文档可能就不能以DOM方式读取,SAX解析则不存在这样的问题,并且SAX解析的速度要比DOM快一些。
2. SAX解析方式
在C#中,使用SAX进行解析的类为XmlReader, XmlWriter,这两个类都是抽象类,由具体的子类来实现相关的功能。
具体的子类: XmlTextReader, XmlTextWriter
接下来简单看看XmlReader的成员:
Name | Description | |
---|---|---|
Close | When overridden in a derived class, changes the ReadState to Closed. | |
Create(Stream) | Creates a new XmlReader instance using the specified stream. | |
Create(String) | Creates a new XmlReader instance with specified URI. | |
Create(TextReader) | Creates a new XmlReader instance with the specified TextReader. | |
Create(Stream, XmlReaderSettings) | Creates a new XmlReader instance with the specified stream and XmlReaderSettings object. | |
Create(String, XmlReaderSettings) | Creates a new instance with the specified URI and XmlReaderSettings. | |
Create(TextReader, XmlReaderSettings) | Creates a new XmlReader instance using the specified TextReader and XmlReaderSettings objects. | |
Create(XmlReader, XmlReaderSettings) | Creates a new XmlReader instance with the specified XmlReader and XmlReaderSettings objects. | |
Create(Stream, XmlReaderSettings, String) | Creates a new XmlReader instance using the specified stream, base URI, and XmlReaderSettings object. | |
Create(Stream, XmlReaderSettings, XmlParserContext) | Creates a new XmlReader instance using the specified stream, XmlReaderSettings, and XmlParserContext objects. | |
Create(String, XmlReaderSettings, XmlParserContext) | Creates a new XmlReader instance using the specified URI, XmlReaderSettings, and XmlParserContext objects. | |
Create(TextReader, XmlReaderSettings, String) | Creates a new XmlReader instance using the specified TextReader, XmlReaderSettings, and base URI. | |
Create(TextReader, XmlReaderSettings, XmlParserContext) | Creates a new XmlReader instance using the specified TextReader, XmlReaderSettings, and XmlParserContext objects. | |
Dispose | Releases the unmanaged resources used by the XmlReader and optionally releases the managed resources. | |
Equals(Object) | Determines whether the specified Object is equal to the current |