These tutorials demonstrate selected features in ASP.NET version 2.0, but they are compatible with later versions of ASP.NET as well. For the current documentation, see the ASP.NET portal on the MSDN Web site.

 

 

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

How Do I...? Common Tasks QuickStart Tutorial

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.

VB XmlDocumentEvent.exe
View Source

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.

		
Dim xmlDocument as XmlDocument  = new XmlDocument()
xmlDocument.Load (args)
VB

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.

		
AddHandler xmlDocument.NodeChanged, new XmlNodeChangedEventHandler(addressof NodeChangedEvent)
AddHandler xmlDocument.NodeInserted, new XmlNodeChangedEventHandler(addressof NodeInsertedEvent)
VB

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
Dim xmlNodeList As XmlNodeList = xmlDocument.SelectNodes("descendant::book/price")

Dim xmlNode As XmlNode
For Each xmlNode In xmlNodeList
    Console.WriteLine("<" + xmlNode.Name + "> " + xmlNode.InnerText)
    Dim price As [Double] = [Double].Parse(xmlNode.InnerText)
    xmlNode.InnerText = (CType(price, [Double]) * 1.02).ToString("#.00")
Next xmlNode
VB

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
Dim newBook as XmlDocumentFragment  = myXmlDocument.CreateDocumentFragment()

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

Dim rootXmlElement as XmlElement  = myXmlDocument.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
Dim newBook2 as XmlNode  = xmlDocument.DocumentElement.FirstChild.Clone()
VB

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

		
' Handle the Node Changed Event
public sub NodeChangedEvent(src as Object , args as XmlNodeChangedEventArgs )
    Console.Write("Node Changed Event: <" + args.Node.Name + "> changed")
    if not (args.Node.Value is Nothing) then
        Console.WriteLine(" with value " + args.Node.Value)
    else
        Console.WriteLine("")
    end if
end sub

' Handle the Node Inserted Event
public sub NodeInsertedEvent(src as Object , args as XmlNodeChangedEventArgs )
    Console.Write("Node Inserted Event: <" + args.Node.Name + "> inserted")
    if not (args.Node.Value is Nothing) then
        Console.WriteLine(" with value " + args.Node.Value)
    else
        Console.WriteLine("")
    end if
end sub
VB

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.