Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata