Gestione degli eventi in un documento XML con XmlNodeChangedEventArgs

Gli argomenti passati ai gestori di eventi registrati sull'oggetto XmlDocument per la gestione degli eventi sono incapsulati in XmlNodeChangedEventArgs. Nella tabella seguente sono riportati gli eventi e una descrizione di quando questi vengono generati.

Evento Generato
NodeInserting Quando un nodo appartenente al documento corrente sta per essere inserito in un altro nodo.
NodeInserted Quando un nodo appartenente al documento corrente è stato inserito in un altro nodo.
NodeRemoving Quando un nodo appartenente a questo documento sta per essere rimosso dal documento.
NodeRemoved Quando un nodo appartenente a questo documento è stato rimosso dal padre.
NodeChanging Quando il valore di un nodo sta per essere modificato.
NodeChanged Quando il valore di un nodo è stato modificato.

**Nota   **Se l'utilizzo della memoria di XmlDataDocument è completamente ottimizzato per l'utilizzo dell'archiviazione DataSet, è possibile che nessuno degli eventi precedenti venga generato dall'XmlDataDocument quando vengono apportate modifiche al DataSet sottostante. Se questi eventi sono necessari, deve essere attraversato l'intero XmlDocument per rendere l'utilizzo della memoria non completamente ottimizzato.

Nell'esempio di codice seguente viene illustrato come definire un gestore di eventi e come aggiungere tale gestore a un evento.

' Attach the event handler, NodeInsertedHandler, to the NodeInserted
' event.
Dim doc as XmlDocument = new XmlDocument()
Dim XmlNodeChgEHdlr as XmlNodeChangedEventHandler = new XmlNodeChangedEventHandler(addressof MyNodeChangedEvent) 
AddHandler doc.NodeInserted, XmlNodeChgEHdlr 

Dim n as XmlNode = doc.CreateElement( "element" )
Console.WriteLine( "Before Event Inserting" ) 

' This is the point where the new node is being inserted in the tree,
' and this is the point where the NodeInserted event is raised.
doc.AppendChild( n )
Console.WriteLine( "After Event Inserting" ) 

' Define the event handler that handles the NodeInserted event.
sub NodeInsertedHandler(src as Object, args as XmlNodeChangedEventArgs)
    Console.WriteLine("Node " + args.Node.Name + " inserted!!")
end sub
[C#]
// Attach the event handler, NodeInsertedHandler, to the NodeInserted
// event.
XmlDocument doc = new XmlDocument();
doc.NodeInserted += new XmlNodeChangedEventHandler(NodeInsertedHandler);
XmlNode n = doc.CreateElement( "element" );
Console.WriteLine( "Before Event Inserting" );

// This is the point where the new node is being inserted in the tree,
// and this is the point where the NodeInserted event is raised.
doc.AppendChild( n );
Console.WriteLine( "After Event Inserting" ); 

// Define the event handler that handles the NodeInserted event.
void NodeInsertedHandler(Object src, XmlNodeChangedEventArgs args)
{
    Console.WriteLine("Node " + args.Node.Name + " inserted!!");
}

Alcune operazioni del DOM sono operazioni composte in grado di generare più eventi. È possibile ad esempio che AppendChild debba rimuovere anche il nodo che viene accodato dal suo precedente padre. In questo caso, si osserverà prima la generazione di un evento NodeRemoved, seguito da un evento NodeInserted. Operazioni come l'impostazione di InnerXml possono generare più eventi.

Nell'esempio di codice seguente viene illustrata la creazione del gestore eventi e la gestione dell'evento NodeInserted.

Imports System
Imports System.IO
Imports System.Xml
Imports Microsoft.VisualBasic

public class Sample

  private const filename as String = "books.xml"

  shared sub Main()
     Dim mySample as Sample = new Sample()
     mySample.Run(filename)
  end sub

  public sub Run(args as String)
     ' Create and load the XML document.
     Console.WriteLine ("Loading file 0 ...", args)
     Dim doc as XmlDocument = new XmlDocument()
     doc.Load (args)

     ' Create the event handlers.
     Dim XmlNodeChgEHdlr as XmlNodeChangedEventHandler = new XmlNodeChangedEventHandler(addressof MyNodeChangedEvent) 
     Dim XmlNodeInsrtEHdlr as XmlNodeChangedEventHandler = new XmlNodeChangedEventHandler(addressof MyNodeInsertedEvent)  
     AddHandler doc.NodeChanged, XmlNodeChgEHdlr  
     AddHandler doc.NodeInserted, XmlNodeInsrtEHdlr

     ' Change the book price.
     doc.DocumentElement.LastChild.InnerText = "5.95"

     ' Add a new element.
     Dim newElem as XmlElement = doc.CreateElement("style")
     newElem.InnerText = "hardcover"    
     doc.DocumentElement.AppendChild(newElem)    

     Console.WriteLine(Chr(13) + Chr(10) + "Display the modified XML...")
     Console.WriteLine(doc.OuterXml)
  end sub

  ' Handle the NodeChanged event.
  public sub MyNodeChangedEvent(src as Object, args as XmlNodeChangedEventArgs)
     Console.Write("Node Changed Event: <0> changed", args.Node.Name)
     if Not (args.Node.Value is Nothing)
        Console.WriteLine(" with value  0", args.Node.Value) 
     else
       Console.WriteLine("") 
     end if
  end sub   

  ' Handle the NodeInserted event.
  public sub MyNodeInsertedEvent(src as Object, args as XmlNodeChangedEventArgs)
     Console.Write("Node Inserted Event: <0> inserted", args.Node.Name)
     if Not (args.Node.Value is Nothing)
        Console.WriteLine(" with value 0", args.Node.Value) 
     else
        Console.WriteLine("")
     end if 
  end sub

end Class        ' End class
[C#]
using System;
using System.IO;
using System.Xml;

public class Sample
{
  private const String filename = "books.xml";

  public static void Main()
  {
     Sample mySample = new Sample();
     mySample.Run(filename);
  }

  public void Run(String args)
  {
     
     // Create and load the XML document.
     Console.WriteLine ("Loading file {0} ...", args);
     XmlDocument doc = new XmlDocument();
     doc.Load (args);

     // Create the event handlers.
     doc.NodeChanged += new XmlNodeChangedEventHandler(this.MyNodeChangedEvent);
     doc.NodeInserted += new XmlNodeChangedEventHandler(this.MyNodeInsertedEvent);

     // Change the book price.
     doc.DocumentElement.LastChild.InnerText = "5.95";

     // Add a new element.
     XmlElement newElem = doc.CreateElement("style");
     newElem.InnerText = "hardcover";
     doc.DocumentElement.AppendChild(newElem);

     Console.WriteLine("\r\nDisplay the modified XML...");
     Console.WriteLine(doc.OuterXml);           

  }

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

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

} // End class 

Per ulteriori informazioni, vedere Membri XmlNodeChangeEventArgs e Delegato XmlNodeChangedEventHandler.

Vedere anche

Modello a oggetti di documenti XML (Document Object Model, DOM)