July 21, 2011, 6:55 a.m.
posted by bert
Detecting Changes to an XML Document
You need to inform one or more classes or components that a node in an XML document has been inserted or removed or had its value changed.
In order to track changes to an active XML document, subscribe to the events published by the XmlDocument class. XmlDocument publishes events for node creation, insertion, and removal for both the pre- and post-conditions of these actions.
Figure shows a number of event handlers defined in the same scope as the DetectXMLChanges method, but they could just as easily be callbacks to functions on other classes that are interested in the manipulation of the live XML document.
DetectXMLChanges loads an XML fragment you define in the method; wires up the event handlers for the node events; adds, changes, and removes some nodes to trigger the events; then writes out the resulting XML.
Detecting changes to an XML document
Figure shows the event handlers from the XmlDocument, along with one formatting method, WriteNodeInfo. This method takes an action string and gets the name and value of the node being manipulated. All of the event handlers invoke this formatting method, passing the corresponding action string.
XMLDocument event handlers and WtiteNodeInfo method
Element: <Node5> inserting with null value Element: <Node5> inserted with null value Element: <#text> inserting with value Fifth Element Element: <#text> inserted with value Fifth Element Element: <#text> changing with value First Node Element: <#text> changed with value 1st Node Element: <Node4> removing with null value Element: <Node4> removed with null value <?xml version="1.0"?><!-- My sample XML --><?pi myProcessingInstruction?><Root>< Node1 nodeId="1">1st Node</Node1><Node2 nodeId="2">Second Node</Node2><Node3 nod eId="3">Third Node</Node3><Node5>Fifth Elementy/Node5></Root>
With an XmlDocument, you can traverse both forward and backward in the XML stream, as well as use XPath navigation to find nodes. If you are just reading XML and not modifying it, and you have no need for traversing backward through the nodes, you should avoid using XmlDocument, since XmlReader is faster for reading and XmlWriter is faster for writing (both have less overhead than XmlDocument). The .NET Framework team did a nice job of giving XML processing flexibility, but if you use a class with more functionality than you need, you will pay the resulting performance penalty.
See the "XmlDocument Class" and "XmlNodeChangedEventHandler Class" topics in the MSDN documentation.