使用 XPathDocument 和 XmlDocument 读取 XML 数据

可通过两种方法读取命名空间中的 System.Xml.XPath XML 文档。 一个是使用只读的XPathDocument类读取 XML 文档,另一个是使用XmlDocument命名空间中的可编辑的System.Xml类读取 XML 文档。

使用 XPathDocument 类读取 XML 文档

XPathDocument 类使用 XPath 数据模型提供 XML 文档的快速只读内存中表示形式。 类的 XPathDocument 实例是使用其六个构造函数之一创建的。 通过这些构造函数,可以使用 StreamTextReaderXmlReader 对象来读取 XML 文档,或者使用指向 XML 文件的 string 路径。

以下示例演示如何使用 XPathDocument 类的 string 构造函数读取 XML 文档。

Dim document As XPathDocument = New XPathDocument("books.xml")  
XPathDocument document = new XPathDocument("books.xml");  

使用 XmlDocument 类读取 XML 文档

XmlDocument 类是实现 W3C 文档对象模型 (DOM) 级别 1 核心和核心 DOM 级别 2 的 XML 文档的可编辑内存中表示形式。 类的 XmlDocument 实例是使用其三个构造函数之一创建的。 可以通过调用没有参数的XmlDocument类构造函数来创建新的空XmlDocument对象。 调用构造函数后,使用Load方法将 XML 数据从XmlDocumentStreamTextReader对象,以及 XML 文件路径XmlReader加载到新string对象中。

下面的示例演示如何使用 XmlDocument 没有参数的类构造函数和 Load 读取 XML 文档的方法。

Dim document As XmlDocument = New XmlDocument()  
document.Load("books.xml")  
XmlDocument document = new XmlDocument();  
document.Load("books.xml");  

确定 XML 文档的编码

XmlReader对象可用于读取 XML 文档和创建XPathDocumentXmlDocument对象,如前几节所示。 但是,对象 XmlReader 可能会读取未编码的数据,因此不提供任何编码信息。

XmlTextReader 类继承自 XmlReader 该类,使用其 Encoding 属性提供编码信息,并可用于创建 XPathDocument 对象或 XmlDocument 对象。

有关XmlTextReader类提供的编码信息的详细信息,请参阅Encoding类参考文档中的XmlTextReader属性。

创建 XPathNavigator 对象

将 XML 文档读入 XPathDocument 某个或 XmlDocument 对象后,可以创建一个 XPathNavigator 对象来选择、评估、导航,在某些情况下编辑基础 XML 数据。

除了XPathDocument类之外,类XmlDocumentXmlNode还实现IXPathNavigable命名空间的System.Xml.XPath接口。 因此,这三个类都提供一个 CreateNavigator 返回对象 XPathNavigator 的方法。

使用 XPathNavigator 类编辑 XML 文档

除了选择、计算和导航 XML 数据之外, XPathNavigator 类还可用于根据创建 XML 文档的对象来编辑 XML 文档。

XPathDocument类是只读的,而XmlDocument类是可编辑的,因此,从XPathNavigator对象创建的XPathDocument对象不能用于编辑XML文档,而从XmlDocument对象创建的对象则可以。 类 XPathDocument 应仅用于读取 XML 文档。 如果您需要编辑 XML 文档,或者需要访问由XmlDocument类提供的额外功能(例如事件处理),那么应使用XmlDocument类。

CanEdit 的属性 XPathNavigator 指定对象 XPathNavigator 是否可以编辑 XML 数据。

下表描述了每个类的属性 CanEdit 的值。

IXPathNavigable 实现 CanEdit
XPathDocument false
XmlDocument true

另请参阅