O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

17.6. Detecting Changes to an XML Document

Problem

You need to inform one or more classes or components that a node in an XML document has been inserted, removed, or had its value changed.

Solution

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. In the following example, we have 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 we 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:

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 += new XmlNodeChangedEventHandler(NodeChangedEvent); doc.NodeInserting += new XmlNodeChangedEventHandler(NodeInsertingEvent); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required