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); ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.