
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Detecting Changes to an XML Document
|
847
Solution
In order to track changes to an active XML document, subscribe to the events pub-
lished 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 trig-
ger the events; then writes out the resulting XML.
Example 15-4. Detecting changes to an XML document
public static void DetectXmlChanges( )
{
string xmlFragment = "<?xml version='1.0'?>" +
"<!-- My sample XML -->" +
"<?pi myProcessingInstruction?>" +
"<Root>" +
"<Node1 nodeId='1'>First Node</Node1>" +
"<Node2 nodeId='2'>Second Node</Node2>" +
"<Node3 nodeId='3'>Third Node</Node3>" +
@"<Node4><![CDATA[<>\&']]></Node4>" +
"</Root>";
XmlDocument doc = new XmlDocument( );
doc.LoadXml(xmlFragment);
//Create the event handlers.
doc.NodeChanging += new XmlNodeChangedEventHandler(NodeChangingEvent);
doc.NodeChanged ...