Welcome   |   ASP.NET   |   Web Services   |   How Do I...?   |   Class Browser
  |   I want my samples in...   

How Do I...? Common Tasks QuickStart Tutorial

Go To...

How Do I...Handle Events from XmlDocument?

This sample illustrates how to receive and handle events when nodes in an XML document change. In particular, this sample demonstrates how to catch the NodeChanged and NodeInserted events described in the following paragraphs.

Modifying an XmlDocument can result in one or more of the following events:

  • The NodeInserted event occurs when any node belonging to XmlDocument has been inserted into another node. This includes all nodes that were created by this document, whether they are inside or outside the document tree, including attribute nodes.
  • The NodeRemoved event occurs when any node belonging to this document has been removed from its parent. This includes all nodes that were created by this document, whether they are inside or outside the document tree, including attribute nodes.
  • The NodeChanged event occurs when the Value property of any node belonging to this document has been changed. This applies only to nodes that have a Value property.
  • The NodeInserting, NodeRemoving, or NodeChanging events occur when any node belonging to this document is about to be inserted, removed, or changed.

These events enable you to throw an exception if you want to stop the operation. The XmlDocument guarantees that, after throwing the exception, the document is in the state it was in before the operation was started.

C# XmlDocumentEvent.exe
View Source

[This sample can be found at M:\web\users\Sites\AspnetQuickStart\v2.0\QuickStart\howto\samples\Xml\XmlDocumentEvent\
To build this sample, open the SDK command prompt and navigate to the above path. Build the sample using the build tool msbuild passing the solution file as the first parameter: msbuild mySample.sln. The compiled executable will be found in the sub directory \bin directory.]

After loading the books.xml file into an XmlDocument, this sample application both modifies the price of the existing books within the document and adds new books to the document. These changes result in NodeChanged and NodeInserted events.

The following sample code constructs an XmlDocument and loads books.xml.

		
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load (args);
C#

When the sample loads books.xml, the sample adds the NodeChanged and a NodeInserted event handlers the XmlDocument. The code for these handlers appears later in this topic.

		
xmlDocument.NodeChanged += new XmlNodeChangedEventHandler(this.NodeChangedEvent);
xmlDocument.NodeInserted += new XmlNodeChangedEventHandler(this.NodeInsertedEvent);
C#

The sample application changes data with the document by increasing the price of each book by 2%. To do this, the sample must first select the data to be changed by using the SelectNodes method of the XmlNode class. By using the XML Path Language (Xpath) expression "descendant::book/price", with the SelectNodes method, the sample selects the price child elements of all the book elements. The application then places these selected nodes into an XmlNodeList where they can be edited to reflect a 2% price increase. This price increase operation consists of getting the InnerText value of the price element, increasing it by 2%, and then inserting the modified value back into the element. Each time the price element changes, there is a NodeChanged event that writes the new price to the screen. The code for the NodeChanged event appears later in this topic.

		
// Increase all the book prices by 2%
...
// Create a list of the  nodes and change their values
XmlNodeList xmlNodeList = xmlDocument.SelectNodes("descendant::book/price");

foreach (XmlNode xmlNode in xmlNodeList)
{
    Console.WriteLine("<" + xmlNode.Name + "> " + xmlNode.InnerText);
    Double price = Double.Parse(xmlNode.InnerText);
    xmlNode.InnerText = (((Double)price * 1.02).ToString("#.00"));
}
C#

The sample application also inserts a node into the XmlDocument. A simple way to insert a new node is to create an XmlDocumentFragment, determine where in the document you want to insert the fragment, and then use the InsertBefore or InsertAfter methods of the XmlDocument. As shown in the following code, the sample creates the XmlDocumentFragment with a string of prepared XML and then inserts this fragment into myXmlDocument. By inserting a new node, there is a NodeInserted event that writes the new node information to the screen. The code for the NodeInserted event appears later in this topic.

		
// Create a new book
XmlDocumentFragment newBook = xmlDocument.CreateDocumentFragment();

newBook.InnerXml = ("" +
  "Design Patterns - Elements of Reusable Object-Orientated Software" +
  "" +
  "Eric" +
  "Gamma" +
  "" +
  "49.95" +
  "");

XmlElement rootXmlElement = xmlDocument.DocumentElement;

// Add the new book to the XmlDocument
rootXmlElement.InsertBefore(newBook, rootXmlElement.FirstChild);
...
// Clone the node and note that by cloning the node we
// are inserting it again into the XmlDocument
XmlNode newBook2 = xmlDocument.DocumentElement.FirstChild.Clone();
C#

The following code describes the functions that handle the NodeChanged and NodeInserted events.

		
// Handle the Node Changed Event
public void NodeChangedEvent(Object src, XmlNodeChangedEventArgs args)
{
    Console.Write("Node Changed Event: <" + args.Node.Name + "> changed");
    if (args.Node.Value != null)
    {
        Console.WriteLine(" with value " + args.Node.Value);
    }
    else
        Console.WriteLine("");
}

// Handle the Node Inserted Event
public void NodeInsertedEvent(Object src, XmlNodeChangedEventArgs args)
{
    Console.Write("Node Inserted Event: <" + args.Node.Name + "> inserted");
    if (args.Node.Value != null)
    {
        Console.WriteLine(" with value " + args.Node.Value);
    }
    else
        Console.WriteLine("");
}
C#

Summary

  1. To edit node values, first use SelectNodes to select the nodes and then place the selected nodes into an XmlNodeList.
  2. There are six node events that can be handled: NodeInserted, NodeRemoved, NodeChanged, NodeInserting, NodeRemoving, or NodeChanging.
  3. To handle nodes, add the node handler to your instance of XmlDocument.




Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2005 Microsoft Corporation. All rights reserved.


Hosted by MaximumASP | Found a broken link? | Contact Us | Terms and conditions | Privacy Policy | Advertise with us
� 2000 - 2008  Mindcracker LLC. All Rights Reserved