共用方式為


Load Data from a Reader

If the document is loaded using the Load method and a parameter of an XmlReader, there are differences in the behavior that occurs when compared to the behavior of loading data from the other formats. If the reader is in its initial state, which is checked by seeing if the ReadState property equals ReadState.Initial, Load consumes the entire contents from the reader and builds the DOM from all the data in the reader.

If the reader is already positioned on a node somewhere in the document, and then the reader is passed to the Load method, Load attempts to read the current node and all of its siblings. This is done up to the end tag that closes the current depth, into memory. The success of Load depends on the node that the reader is on when the load is attempted, as Load verifies that the XML from the reader is well-formed. If the XML is not well-formed the Load throws an exception. For example, the following set of nodes contain two root level elements and the XML is not well-formed and Load throws an exception.

  • Comment node, followed by an Element node, followed by an Element node, followed by an EndElement node.

The following set of nodes creates an incomplete DOM, because there is no root level element.

  • Comment node followed by a ProcessingInstruction node followed by a Comment node followed by an EndElement node.

This does not throw an exception, and the data is loaded. You can add a root element to the top of these nodes and create well-formed XML that can be saved without error.

If the reader is positioned on a leaf node that is invalid for the root level of a document, for example a white space or attribute node, the reader continues to read until it is positioned on a node that can be used for the root. The document begins loading at this point.

By default, Load does not check if the XML is valid using DTD or schema validation. It only checks if the XML is well-formed. In order for validation to occur, you need to pass in an XmlValidatingReader, specify the appropriate ValidationType, and provide a ValidationEventHandler. For more information on the XmlValiatingReader, see Validation of XML with XmlValidatingReader. For more information on event handling, see Event Handling in an XML Document Using the XmlNodeChangedEventArgs.

See Also

XML Document Object Model (DOM)