Properties and Methods for the XPathDocument2 Class and Dependent Classes



Properties and Methods for the XPathDocument2 Class and Dependent Classes

Before we look at more examples of using the XPathDocument2 class, this section contains a concise reference to all its properties and methods.

In System.Xml 1.x there is an XPathDocument class that is identical to the XPathDocument2 class but is a read-only XML store.

In this Technology Preview release, the XPathDocument2 class is an editable XML in-memory store. This is due to be combined with the XPathDocument class in the next release, so that there will be only a single in-memory store based on the XPath data model.

Constructors

The constructors for XPathDocument2 create a new instance of the class (see Figure).

The Constructors for the XPathDocument2 Class

Constructor

Description

XPathDocument2()

Creates a new empty XPathDocument2 instance.

XPathDocument2(Boolean)

Creates a new empty XPathDocument2 instance with the Boolean value indicating whether the XPathDocument2 should set up a default root document node. This is useful when storing XML fragments and is typically used in advanced scenarios where XML fragments are loaded into memory for querying or manipulation.

XPathDocument2 (XmlNameTable)

Creates a new empty XPathDocument2 instance with an XmlNameTable. The name table is used during edit operations to atomize element and attribute names. The XmlName Table is an optimization. By sharing this across components it allows for faster lookup of attribute and element names. For example, if the XPathDocument2 is loaded from an Xml Reader, the XmlNameTable from the Xml Reader can be set onto the XPathDocument2 for decreased load time, with the performance improvement depending entirely on the type of XML document.

XPathDocument2 XPathDocument2 (XmlNameTable, Boolean)

Creates a new empty instance with a combination of the XmlNameTable and default root options.

Properties

The properties of the XPathDocument2 class are shown in Figure.

Methods

The methods of the XPathDocument2 class are shown in Figure.

The Properties of the XPathDocument2 Class

Property

Description

AcceptChangesOnLoad

Specifies whether the document automatically calls AcceptChanges after a load operation, i.e., whether the load keeps the pending changes or replaces them with the new values. Setting this to False causes any loaded XML to be treated as one big insert operation.

DefaultRoot

Returns a Boolean value indicating whether the XPathDocument2 was instantiated to have a default root node or not.

NameTable

Returns a reference to the XmlNameTable for the XPathDocument2. If the XPathDocument2 was loaded using the XmlReader, this name table will be the one obtained from the XmlReader. If not, a new XmlNameTable is created by default when the XPathDocument2 is created.

The Methods of the XPathDocument2 Class

Method

Description

AcceptChanges()

Commits all changes made to all the nodes since the last time AcceptChanges or RejectChanges was called (or the last time AcceptChange or RejectChange was called on each node). Calling AcceptChanges has the following effects on the nodes:

  • Inserted nodes: The node is no longer marked as Inserted; i.e., the XmlNodeChangeType enumeration value for this node is set to Unchanged and the current value of the node is then propagated to the original value of the node.

  • Deleted nodes: The node and its subtree are no longer accessible from the main tree using the XPath Navigator2, XPathEditor, or XPathChange Navigator classes.

  • Updated nodes: The node is no longer marked as Updated; i.e., the XmlNodeChangeType for this node is set to Unchanged, and the current value of the node is propagated to the original value for the node.

CheckValidity(schemas, ValidationEventHandler)

Checks that the XPathDocument2 conforms to the specified schema(s) but does not perform schema PSVI InfoSet augmentation. (PSVI is Post Validation Schema Information—the information that an XML schema adds to a document as a result of the validation process.) This means that schema defaults such as default attributes are not applied to the document. The XPathDocument2 is unchanged by this method. The ValidationEventHandler parameter is the registered callback event handler that receives information about schema validation errors and warnings.

CreateXPathChangeNavigator()

Creates and returns a new XPathChange Navigator instance positioned at the root node. This XPathChangeNavigator can navigate through all the Updated, Inserted, Deleted, and Unchanged nodes and access the current and original values of a node where applicable. If there is no root node, an XmlException is thrown.

CreateXPathEditor()

Returns a new XPathEditor class positioned at the root node. The XPathEditor provides a cursor API for editing the XPathDocument2. The tree navigated is the current view that does not include any deleted nodes. If there is no root node, an XmlException is thrown.

CreateXPathNavigator2()

Returns a new XPathNavigator2 class positioned at the root node. The XPath Navigator2 provides a cursor API for read-only navigation of the XPathDocument2. The tree navigated is the current view that does not include any deleted nodes. If there is no root node, an XmlException is thrown.

HasChanges()

Returns a Boolean value indicating whether here are pending changes on the XPath ocument2. The second overload for this method accepts a parameter and returns True only if there are any pending changes in the XPathDocument2 that match the specified value from the XmlChangeFilters enumeration:

HasChanges (ChangeFilter)

IsDeletedFragment (XPathNavigator)

Used to check whether the specified XPathNavigator is referencing a node that is part of a deleted subtree. Returns a Boolean value that is True if the subtree for the XPathNavigator2 has been deleted from the XPathDocument2. The table below shows the return values. ("Permanently deleted" means that after this subtree was deleted the AcceptChanges method has been called.)

 

XPathNavigator Pointing to Deleted Node?

Permanently Deleted?

Return Value

No

No

False

Yes

No

True

No

Yes

True

Yes

Yes

True

 

The second overload of this method also accepts a parameter that defines a node that is permanently deleted:

 

IsDeletedFragment(XPathNavigator, is-permanent)

 

The table below shows the return values when is-permanent = true.

 

XPathNavigator Pointing to Deleted Node?

Permanently Deleted?

Return Value

No

No

False

Yes

No

True

Yes

Yes

True

 

The table below shows the return values when is-permanent = false.

 

XPathNavigator Pointing to Deleted Node?

Permanently Deleted?

Return Value

No

No

False

Yes

No

True

Yes

Yes

True

Load(parameter)

Loads XML data into the XPathDocument2. There are four overloads of this method:

  • Load(file-name): Loads the data from the specified file.

  • Load(Stream): Loads a stream containing XML data.

  • Load(reader): Loads the XML from an XmlReader.

  • Load(TextReader): Loads from a TextReader containing XML data.

LoadXml(xml-markup)

Loads the XPathDocument2 with the given xml-markup string that is well-formed XML.

RejectChanges()

Rejects all changes made to all the nodes since the last time AcceptChanges or RejectChanges was called (or the last time AcceptChange or RejectChange was called on each node). Calling RejectChanges has the following effects on the nodes:

  • Inserted nodes: The node and its subtree are no longer accessible from the main tree using the XPath Navigator2, XPathEditor, or XPathChange Navigator classes.

  • Deleted nodes: The node is no longer marked as Deleted; i.e., the XmlNodeChangeType for this node is set to Unchanged; and the current value of the node is changed to the original value of the node.

  • Updated nodes: The node is no longer marked as Updated; i.e., the XmlNodeChangeType for this node is set to Unchanged, and the current value of the node is changed to the original value of the node.

Save(parameter)

Saves the XML data from the XPathDocument2. There are three overloads of this method:

  • Save(file-name): Saves the XML to the specified file.

  • Save(Stream): Saves the XML to the specified stream.

  • Save(TextWriter): Saves the XML to the specified TextWriter.

Events

The events of the XPathDocument2 class are shown in Figure. Generally, edit operations cannot occur inside an event ending in -ing, only in events ending in -ed. The events are useful for applying business rules when the state of the XPathDocument2 changes. For example, if each new ISBN attribute inserted has to be checked against a regular expression, code that handles the ItemInserting event can apply that regular expression to check for validity.

Of course, in this case it could also be enforced by a schema for the ISBN attribute and validated by calling the CheckValidity method on the XPathDocument2. Events can also be used to apply constraints across the document, for example, that you can write a price element for a book only if it has both publicationdate and ISBN attributes.

Also note the XPathDocument2 guarantees that, after an exception is thrown (e.g., to cancel a process), the document is left in the state prior to the operation starting.

The Events of the XPathDocument2 Class

Event

Description

ItemInserting

Occurs when any node belonging to this document is about to be inserted into another node. This allows for extra checking and the ability to throw an exception if the operation should be canceled. The event handler receives an XPathDocument2 ChangedEventArgs containing information related to this event.

ItemInserted

Occurs after a node has been inserted in this document. This includes all nodes created by this document, whether they were in the document tree or outside the tree, and includes attribute nodes. The event handler receives an XPathDocument2 ChangedEventArgs containing information related to this event.

ItemRemoving

Occurs when any node belonging to this document is about to be removed from its parent. This allows for extra checking and the ability to throw an exception if the operation should be canceled. The event handler receives an XPathDocument2 ChangedEventArgs containing information related to this event.

ItemRemoved

Occurs after a node belonging to this document has been removed from its parent. This includes all nodes that were created by this document, whether they were in the document tree or outside the tree, and includes attribute nodes. The event handler receives an XPathDocument2ChangedEventArgs containing information related to this event.

ItemChanging

Occurs when the value of any item belonging to this document is about to be changed. Applies only to nodes that have a value. This allows for extra checking and the ability to throw an exception if the operation should be canceled. The event handler receives an XPathDocument2ChangedEventArgs containing information related to this event.

ItemChanged

Occurs when the value of any item belonging to this document has been changed. Applies only to nodes that have a value. Includes all nodes that were created by this document, whether they were in the document tree or outside the tree, and includes attribute nodes. The event handler receives an XPath Document2ChangedEventArgs containing information related to this event.

RejectingChange

Occurs when a change to any item belonging to this document is about to be rejected by means of the RejectChanges method. Applies only to nodes that have been changed. This allows for extra checking and the ability to throw an exception if the operation should be canceled. The event handler receives an XPath Document2ChangedEventArgs containing information related to this event.

ChangeRejected

Occurs when a change to any item belonging to this document is rejected by means of the RejectChanges method. Applies only to nodes that have been changed. The event handler receives an XPathDocument2ChangedEventArgs containing information related to this event.

The XPathDocument2ChangedEventArgs Class

The events of the XPathDocument2 class are returned via the registered delegate class XPathDocument2ChangedEventHandler. The signature of this class returns an XPathDocument2ChangedEventArgs instance containing information about the changed item within the tree, as shown in Figure. The properties of this class can be used to create the required business logic around the event.

The Properties of the XPathDocument2ChangedEventArgs Class

Property

Description

Action

A value from the XPathDocument2ChangedEventAction enumeration indicating the type of node change event. See Figure.

Item

An XPathNavigator2 instance pointing to the item that is being acted on.

OldValue

A String containing the old value of the text or attribute node being updated. Contains Nothing (null in C#) for insert and delete operations.

NewValue

A String containing the new value of the text or attribute node being updated. Contains Nothing (null in C#) for insert and delete operations.

OldParent

An XPathNavigator2 instance pointing to the result of the call to the MoveToParent method that takes place on the node being deleted before the delete operation takes place. Contains Nothing (null in C#) for insert operations if the node does not have a parent beforehand. This is the same as the NewParent property if a change occurred. For attribute nodes this is the owning element.

NewParent

An XPathNavigator2 instance pointing to the result of the MoveToParent method that takes place on the node being changed.

OldPreviousItem

For delete operations this is an XPathNavigator2 instance pointing to the node that was the previous sibling of the node being deleted or updated. For insert operations this is Nothing (null in C#). For update operations this is the same as the NewPreviousItem property.

NewPreviousItem

For insert operations this is an XPathNavigator2 instance pointing to the node that will become the previous sibling of the node being inserted or updated. For delete operations this is Nothing (null in C#). For update operations this is the same as the OldPreviousItem property.

Enumerations

The various properties and methods described in the preceding subsections of this chapter use values from three enumerations:

  1. The XPathDocument2ChangedEventAction enumeration specifies the type of event that is being signaled based on the change that is taking place to the document.

  2. The XmlNodeChangeType enumeration specifies the change status of each node since the last call to the AcceptChanges or Reject Changes method and is returned from the NodeChangeType property of the XPathChangeNavigator class.

  3. The XmlChangeFilters enumeration specifies values that are passed to the SelectChanges method of the XPathChangeNavigator class to retrieve all the nodes that have a value corresponding to the NodeChangeType property. This enumeration allows a bitwise combination of its member values. Hence expressions like Inserted Or Deleted (Inserted | Deleted in C#) can be used to get both the inserted and deleted nodes.

Figure, 6.7, and 6.8 document these enumerations and their values.

The XPathDocument2ChangedEventAction Enumeration

Member

Description

Changing

Indicates that the node is being updated.

Changed

Indicates that the node has been updated.

Inserting

Indicates that the node is being inserted.

Inserted

Indicates that the node has been inserted.

Removing

Indicates that the node is being deleted.

Removed

Indicates that the node has been deleted.

Rejecting

Indicates that the node is being rejected.

Rejected

Indicates that the node has been rejected.

The XmlNodeChangeType Enumeration

Member

Description

Deleted

Indicates that this node has been deleted from the tree. Even though any descendants of this node are no longer part of the current view, their XmlNodeChangeTypes are not automatically set to Deleted but instead are left as they were. The reason for this is to ensure that each delete operation has exactly one node marked as Deleted.

Inserted

Indicates that this node has been inserted. Nodes can be inserted only as leaf nodes, i.e., at the end of a tree. If a node is marked as Inserted, the entire subtree under the node has also been inserted. There is no concept of inserting an entire subtree in one shot. This is equivalent to inserting a node and all its children one by one. Any updates to an inserted node do not affect the XmlNodeChangeType for the current node. If an inserted node is deleted, the node is no longer visible on the XPathChangeNavigator and the node change type is set to Unchanged (i.e., the AcceptChange and RejectChange methods will do nothing if called on this node).

Unchanged

Indicates that this node has not been changed. The AcceptChange and RejectChange methods will do nothing if called on this node.

Updated

Indicates that the value of this node has been changed. This means that it has both original and current values that can be examined as properties of the node.

The XmlChangeFilters Enumeration

Member

Description

Inserted

Used in the SelectChanges method of the XPathChangeNavigator2 class to retrieve nodes that have been inserted. This filter shows the roots of subtrees that have been inserted. Nodes can be inserted only as leaves, so if a node is marked as inserted, the entire subtree below the node has been inserted.

Deleted

Used in the SelectChanges method of the XPathChangeNavigator2 class to retrieve nodes that have been deleted. This filter shows the roots of subtrees that have been deleted. Deleting a node detaches the subtree from the main tree.

Updated

Used in the SelectChanges method of the XPathChangeNavigator2 class to retrieve nodes that have been updated.

AllChanges

Used in the SelectChanges method of the XPathChangeNavigator2 class to retrieve all nodes that have been changed. This is equivalent to calling SelectChanges with Inserted Or Deleted Or Updated (Inserted | Deleted | Updated in C#).

The values in Figure through 6.8 are flags, so you can combine them with filter nodes based on the exact type of change that has occurred. For example, you can specify that you want to see only the inserted and deleted nodes in the tree. Listing 6.3 shows the XPathChangeNavigator class retrieving the inserted and deleted nodes from a document and writing the names of these items to the console.

Retrieving Inserted and Deleted Nodes with an XPathChangeNavigator
Dim nav As XPathChangeNavigator = doc.CreateXPathChangeNavigator()

Dim iter As IEnumerable = nav.SelectChanges( _
    XmlChangeFilters.Inserted Or XmlChangeFilters.Deleted)

Dim item As XPathChangeNavigator

For Each item In iter
  If item.NodeChangeType = XmlNodeChangeType.Inserted Then
    Console.WriteLine("Inserted item: " & item.Name)
  ElseIf item.NodeChangeType = XmlNodeChangeType.Deleted Then
    Console.WriteLine("Deleted item: " & item.Name)
  End If
Next