Recipe 15.6. Detecting Changes to an XML DocumentProblemYou 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. SolutionIn 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. Example 15-4 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. Example 15-4. Detecting changes to an XML document
Example 15-5 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. Example 15-5. XMLDocument event handlers and WtiteNodeInfo method
The DetectXmlChanges method results in the following output: 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 node>1st Node</Node1><Node2 node>Second Node</Node2><Node3 nod e>Third Node</Node3><Node5>Fifth Elementy/Node5></Root> DiscussionWith 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 AlsoSee the "XmlDocument Class" and "XmlNodeChangedEventHandler Class" topics in the MSDN documentation. |