Reading XML Data using XPathDocument and XmlDocument
There are two ways to read an XML document in the System.Xml.XPath namespace. One is to read an XML document using the read-only XPathDocument class and the other is to read an XML document using the editable XmlDocument class in the System.Xml namespace.
The XPathDocument class provides a fast, read-only, in-memory representation of an XML document using the XPath data model. Instances of the XPathDocument class are created using one of its six constructors. These constructors allow you to read an XML document using a Stream, TextReader, or XmlReader object, as well as the
string path to an XML file.
The following example illustrates using the XPathDocument class's
string constructor to read an XML document.
The XmlDocument class is an editable in-memory representation of an XML document implementing W3C Document Object Model (DOM) Level 1 Core and Core DOM Level 2. Instances of the XmlDocument class are created using one of its three constructors. You can create a new, empty XmlDocument object by calling the XmlDocument class constructor with no parameters. After calling the constructor, use the Load method to load XML data into the new XmlDocument object from a Stream, TextReader, or XmlReader object, as well as the
string path to an XML file.
An XmlReader object can be used to read an XML document and to create XPathDocument and XmlDocument objects as shown in the previous sections. However, an XmlReader object may read data that is not encoded and as a result does not provide any encoding information.
After you have read an XML document into either an XPathDocument or XmlDocument object, you can create an XPathNavigator object to select, evaluate, navigate, and in some cases, edit the underlying XML data.
Both the XPathDocument and XmlDocument classes, in addition to the XmlNode class, implement the IXPathNavigable interface of the System.Xml.XPath namespace. As a result, all three classes provide a CreateNavigator method that returns an XPathNavigator object.
In addition to selecting, evaluating, and navigating XML data, the XPathNavigator class can be used to edit an XML document in some cases, based on the object that created it.
The XPathDocument class is read-only while the XmlDocument class is editable and as a result, XPathNavigator objects created from an XPathDocument object cannot be used to edit an XML document while those created from an XmlDocument object can. The XPathDocument class should be used to read an XML document only. In cases where you need to edit an XML document, or require access to the additional functionality provided by the XmlDocument class, like event handling, the XmlDocument class should be used.
The following table describes the value of the CanEdit property for each class.
|IXPathNavigable Implementation||CanEdit Value|