How to handle events from xmldocument
This example illustrates how to receive and process events when a node in the XML document changes. Specifically, this example shows how to capture the nodechanged and nodeinserted events described in the following section.
Modifying xmldocument may cause one or more of the following events:
- When any node of the xmldocument is inserted into another node, the nodeinserted event occurs. This includes all nodes created from this document, whether inside or outside the document tree, including attribute nodes.
- When any node in this document is removed from its parent, the noderemoved event occurs. This includes all nodes created from this document, whether inside or outside the document tree, including attribute nodes.
- The nodechanged event occurs when the value attribute of any node in this document is changed. This applies only to nodes with value attributes.
- Nodeinserting, noderemoving, or nodechanging events occur when any node in this document is to be inserted, removed, or changed.
These events enable you to raise an exception when you want to stop the operation. Xmldocument ensures that after an exception is thrown, the document will return to the status before the operation starts.
|
[Running example] | [View Source Code] |
After loading the books. xml file to xmldocument, this example application modifies the price of Existing Books in the document and adds new books to the document. These changes will cause nodechanged and nodeinserted events.
The following sample code constructs an xmldocument and loads books. xml.
XmlDocument myXmlDocument = new XmlDocument(); myXmlDocument.Load (args); Dim myXmlDocument as XmlDocument = new XmlDocument() myXmlDocument.Load (args) |
C # |
VB |
|
This example adds the nodechanged and nodeinserted event handlers to xmldocument after loading books. xml. (The codes of these handlers will appear in the subsequent sections of this topic .)
myXmlDocument.NodeChanged += new XmlNodeChangedEventHandler(this.MyNodeChangedEvent); myXmlDocument.NodeInserted += new XmlNodeChangedEventHandler(this.MyNodeInsertedEvent); AddHandler myXmlDocument.NodeChanged, new XmlNodeChangedEventHandler(addressof MyNodeChangedEvent) AddHandler myXmlDocument.NodeInserted, new XmlNodeChangedEventHandler(addressof MyNodeInsertedEvent) |
C # |
VB |
|
The sample application changes the data in the document, increasing the price per book by 2%. Therefore, this example must first use the selectnodes method of the xmlnode class to select the data to be changed. The XML Path Language (XPath) expression "Descendant: Book/price" using the selectnodes method is used. In this example, the price child element of all book elements is selected. The application then places these selected nodes in xmlnodelist, where they will be edited to reflect a 2% price increase. To increase the price, follow these steps: Get the innertext value of the price element, increase the value by 2%, and insert the modified value into the element. Each time the price element changes, a nodechanged event will output the new price to the screen. (The code for the nodechanged event will appear in the later part of this topic .)
// Increase all the book prices by 2% ... // Create a list of the
nodes and change their values XmlNodeList myXmlNodeList = myXmlDocument.SelectNodes("descendant::book/price"); foreach (XmlNode myXmlNode in myXmlNodeList) { Console.WriteLine("<" + myXmlNode.Name + "> " + myXmlNode.InnerText); Double price = Double.Parse(myXmlNode.InnerText); myXmlNode.InnerText = (((Double)price * 1.02).ToString("#.00")); }
' Increase all the book prices by 2% ... ' Create a list of the
nodes and change their values Dim myXmlNodeList as XmlNodeList = myXmlDocument.SelectNodes("descendant::book/price") Dim myXmlNode as XmlNode for each myXmlNode in myXmlNodeList Console.WriteLine("<" + myXmlNode.Name + "> " + myXmlNode.InnerText) Dim price as Double = System.Double.Parse(myXmlNode.InnerText) myXmlNode.InnerText = CStr(CType(price * 1.02, Double).ToString("#.00")) next
|
C # |
VB |
|
The sample application also inserts a node into xmldocument. A simple method to insert a new node is to create an xmldocumentfragment, determine the position of the part to be inserted in the document, and then use the insertbefore or insertafter method of xmldocument. As shown in the following code, this example uses the prepared XML string to create xmldocumentfragment, and then inserts this fragment into xmldocument. After a new node is inserted, the nodeinserted event occurs, and the new node information is output to the screen. (The code for the nodeinserted event will appear in the later part of this topic .)
// Create a new book XmlDocumentFragment myNewBook = myXmlDocument.CreateDocumentFragment(); myNewBook.InnerXml = ("
" + "" + "" + "
Eric
" + "
Gamma
" + "" + "
49.95
" + "
"); XmlElement rootXmlElement = myXmlDocument.DocumentElement; // Add the new book to the XmlDocument rootXmlElement.InsertBefore(myNewBook, rootXmlElement.FirstChild); ... // Clone the node and note that by cloning the node we // are inserting it again into the XmlDocument XmlNode myNewBook2 = myXmlDocument.DocumentElement.FirstChild.Clone(); ' Create a new book Dim myNewBook as XmlDocumentFragment = myXmlDocument.CreateDocumentFragment() myNewBook.InnerXml = ("
" & _ "" & _ "" & _ "
Eric
" & _ "
Gamma
" & _ "" & _ "
49.95
" & _ "
") Dim rootXmlElement as XmlElement = myXmlDocument.DocumentElement ' Add the new book to the XmlDocument rootXmlElement.InsertBefore(myNewBook, rootXmlElement.FirstChild) ... ' Clone the node and note that by cloning the node we ' are inserting it again into the XmlDocument Dim myNewBook2 as XmlNode = myXmlDocument.DocumentElement.FirstChild.Clone() |
C # |
VB |
|
The following code describes the functions used to process nodechanged and nodeinserted events.
// Handle the Node Changed Event public void MyNodeChangedEvent(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 MyNodeInsertedEvent(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(""); } ' Handle the Node Changed Event public sub MyNodeChangedEvent(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 MyNodeInsertedEvent(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 |
C # |
VB |
|
Summary
- To edit the node value, use selectnodes to select a node and place the selected node in xmlnodelist.
- There are six node events that can be processed: nodeinserted, noderemoved, nodechanged, nodeinserting, noderemoving, or nodechanging.
- To process a node, you can add the node handler to the xmldocument instance.