XmlSerializer.UnreferencedObject Evento
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Se produce durante la deserialización de una secuencia XML con codificación SOAP, cuando XmlSerializer encuentra un tipo reconocido que no se utiliza o al que no se hace referencia.
public:
event System::Xml::Serialization::UnreferencedObjectEventHandler ^ UnreferencedObject;
public event System.Xml.Serialization.UnreferencedObjectEventHandler UnreferencedObject;
member this.UnreferencedObject : System.Xml.Serialization.UnreferencedObjectEventHandler
Public Custom Event UnreferencedObject As UnreferencedObjectEventHandler
Tipo de evento
Ejemplos
En el ejemplo siguiente se agrega un objeto UnreferencedObjectEventHandler a .XmlSerializer El método controla el Serializer``_``UnreferencedObject
evento. Para ejecutar el ejemplo, corte y pegue el siguiente XML en un archivo denominado "UnrefObj.xml".
<wrapper>
<Group xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="id1" n1:GroupName=".NET" xmlns:n1="http://www.cpandl.com">
</Group>
<Vehicle id="id2" n1:type="Vehicle" xmlns:n1="http://www.w3.org/2001/XMLSchema-instance">
<licenseNumber xmlns:q1="http://www.w3.org/2001/XMLSchema" n1:type="q1:string">ABCD</licenseNumber>
</Vehicle>
<Vehicle id="id3" n1:type="Vehicle" xmlns:n1="http://www.w3.org/2001/XMLSchema-instance">
<licenseNumber xmlns:q1="http://www.w3.org/2001/XMLSchema" n1:type="q1:string">1234</licenseNumber>
</Vehicle>
</wrapper>
#using <System.Xml.dll>
#using <System.dll>
using namespace System;
using namespace System::IO;
using namespace System::Text;
using namespace System::Xml;
using namespace System::Xml::Serialization;
using namespace System::Xml::Schema;
ref class Vehicle;
[SoapInclude(Vehicle::typeid)]
public ref class Vehicle
{
public:
String^ licenseNumber;
};
// You must use the SoapIncludeAttribute to inform the XmlSerializer
// that the Vehicle type should be recognized when deserializing.
[SoapInclude(Vehicle::typeid)]
public ref class Group
{
public:
String^ GroupName;
Vehicle^ GroupVehicle;
};
public ref class Run
{
public:
void DeserializeObject( String^ filename )
{
// Create an instance of the XmlSerializer class.
XmlTypeMapping^ myMapping = ((gcnew SoapReflectionImporter)->ImportTypeMapping( Group::typeid ));
XmlSerializer^ mySerializer = gcnew XmlSerializer( myMapping );
mySerializer->UnreferencedObject += gcnew UnreferencedObjectEventHandler( this, &Run::Serializer_UnreferencedObject );
// Reading the file requires an XmlTextReader.
XmlTextReader^ reader = gcnew XmlTextReader( filename );
reader->ReadStartElement();
// Deserialize and cast the object.
Group^ myGroup;
myGroup = dynamic_cast<Group^>(mySerializer->Deserialize( reader ));
reader->ReadEndElement();
reader->Close();
}
private:
void Serializer_UnreferencedObject( Object^ /*sender*/, UnreferencedObjectEventArgs^ e )
{
Console::WriteLine( "UnreferencedObject:" );
Console::WriteLine( "ID: {0}", e->UnreferencedId );
Console::WriteLine( "UnreferencedObject: {0}", e->UnreferencedObject );
Vehicle^ myVehicle = dynamic_cast<Vehicle^>(e->UnreferencedObject);
Console::WriteLine( "License: {0}", myVehicle->licenseNumber );
}
};
int main()
{
Run^ test = gcnew Run;
test->DeserializeObject( "UnrefObj.xml" );
}
// The file named S"UnrefObj.xml" should contain this XML:
// <Group xmlns:xsi=S"http://www.w3.org/2001/XMLSchema-instance"
//xmlns:xsd=S"http://www.w3.org/2001/XMLSchema" id=S"id1"
//n1:GroupName=S".NET" xmlns:n1=S"http://www.cpandl.com">
//<Vehicle id=S"id2" n1:type=S"Vehicle"
//xmlns:n1=S"http://www.w3.org/2001/XMLSchema-instance">
// <licenseNumber xmlns:q1=S"http://www.w3.org/2001/XMLSchema"
//n1:type=S"q1:String*">ABCD</licenseNumber>
//<Vehicle id=S"id3" n1:type=S"Vehicle"
//xmlns:n1=S"http://www.w3.org/2001/XMLSchema-instance">
// <licenseNumber xmlns:q1=S"http://www.w3.org/2001/XMLSchema"
//n1:type=S"q1:String*">1234</licenseNumber>
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Schema;
// You must use the SoapIncludeAttribute to inform the XmlSerializer
// that the Vehicle type should be recognized when deserializing.
[SoapInclude(typeof(Vehicle))]
public class Group
{
public string GroupName;
public Vehicle GroupVehicle;
}
[SoapInclude(typeof(Vehicle))]
public class Vehicle
{
public string licenseNumber;
}
public class Run
{
public static void Main()
{
Run test = new Run();
test.DeserializeObject("UnrefObj.xml");
}
public void DeserializeObject(string filename)
{
// Create an instance of the XmlSerializer class.
XmlTypeMapping myMapping =
(new SoapReflectionImporter().ImportTypeMapping(
typeof(Group)));
XmlSerializer mySerializer =
new XmlSerializer(myMapping);
mySerializer.UnreferencedObject +=
new UnreferencedObjectEventHandler
(Serializer_UnreferencedObject);
// Reading the file requires an XmlTextReader.
XmlTextReader reader=
new XmlTextReader(filename);
reader.ReadStartElement();
// Deserialize and cast the object.
Group myGroup;
myGroup = (Group) mySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.Close();
}
private void Serializer_UnreferencedObject
(object sender, UnreferencedObjectEventArgs e){
Console.WriteLine("UnreferencedObject:");
Console.WriteLine("ID: " + e.UnreferencedId);
Console.WriteLine("UnreferencedObject: " + e.UnreferencedObject);
Vehicle myVehicle = (Vehicle) e.UnreferencedObject;
Console.WriteLine("License: " + myVehicle.licenseNumber);
}
}
// The file named "UnrefObj.xml" should contain this XML:
// <Group xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
//xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="id1"
//n1:GroupName=".NET" xmlns:n1="http://www.cpandl.com">
//<Vehicle id="id2" n1:type="Vehicle"
//xmlns:n1="http://www.w3.org/2001/XMLSchema-instance">
// <licenseNumber xmlns:q1="http://www.w3.org/2001/XMLSchema"
//n1:type="q1:string">ABCD</licenseNumber>
//<Vehicle id="id3" n1:type="Vehicle"
//xmlns:n1="http://www.w3.org/2001/XMLSchema-instance">
// <licenseNumber xmlns:q1="http://www.w3.org/2001/XMLSchema"
//n1:type="q1:string">1234</licenseNumber>
Imports System.IO
Imports System.Text
Imports System.Xml
Imports System.Xml.Serialization
Imports System.Xml.Schema
' You must use the SoapIncludeAttribute to inform the XmlSerializer
' that the Vehicle type should be recognized when deserializing.
<SoapInclude(GetType(Vehicle))> _
Public Class Group
Public GroupName As String
public GroupVehicle As Vehicle
End Class
Public Class Vehicle
Public licenseNumber As String
End Class
Public Class Run
Shared Sub Main()
Dim test As Run = new Run()
test.DeserializeObject("UnrefObj.xml")
End Sub
Public Sub DeserializeObject(filename As String)
' Create an instance of the XmlSerializer class.
Dim myMapping As XmlTypeMapping = _
(new SoapReflectionImporter().ImportTypeMapping _
(GetType(Group)))
Dim mySerializer As XmlSerializer = _
new XmlSerializer(myMapping)
AddHandler mySerializer.UnreferencedObject, _
AddressOf Serializer_UnreferencedObject
' Reading the file requires an XmlTextReader.
Dim reader As XmlTextReader = _
new XmlTextReader(filename)
reader.ReadStartElement()
' Deserialize and cast the object.
Dim myGroup As Group
myGroup = CType( mySerializer.Deserialize(reader), Group)
reader.ReadEndElement()
reader.Close()
End Sub
Private Sub Serializer_UnreferencedObject _
(sender As object , e As UnreferencedObjectEventArgs)
Console.WriteLine("UnreferencedObject:")
Console.WriteLine("ID: " + e.UnreferencedId)
Console.WriteLine("UnreferencedObject: " + e.UnreferencedObject)
Dim myVehicle As Vehicle = CType(e.UnreferencedObject, Vehicle)
Console.WriteLine("License: " + myVehicle.licenseNumber)
End Sub
End Class
' The XML document should contain this information:
' <Group xmlns:xsi="http:'www.w3.org/2001/XMLSchema-instance"
'xmlns:xsd="http:'www.w3.org/2001/XMLSchema" id="id1"
'n1:GroupName=".NET" xmlns:n1="http:'www.cpandl.com">
'<Vehicle id="id2" n1:type="Vehicle"
'xmlns:n1="http:'www.w3.org/2001/XMLSchema-instance">
' <licenseNumber xmlns:q1="http:'www.w3.org/2001/XMLSchema"
'n1:type="q1:string">ABCD</licenseNumber>
'<Vehicle id="id3" n1:type="Vehicle"
'xmlns:n1="http:'www.w3.org/2001/XMLSchema-instance">
' <licenseNumber xmlns:q1="http:'www.w3.org/2001/XMLSchema"
'n1:type="q1:string">1234</licenseNumber>
Comentarios
El UnreferencedObject evento solo se produce cuando XmlSerializer se usa para deserializar un documento XML que contiene un mensaje SOAP que se ajusta a la sección 5 del documento World Wide Web Consortium, Protocolo simple de acceso a objetos (SOAP) 1.1.
Los documentos que se ajustan a la sección 5 están en un formato especial. Al menos, este documento incluye el cuerpo principal del mensaje SOAP. Sin embargo, en lugar de tener todos los tipos definidos en línea en el documento, algunas definiciones de tipo se pueden codificar como referencias a elementos de nivel superior del documento. Por lo tanto, para cada elemento que se encuentra en el cuerpo principal que es una referencia, debe haber un elemento correspondiente que contenga la definición de tipo. Para correlacionar el elemento de referencia y la definición de tipo, la definición de tipo tiene un id
atributo establecido en un identificador de cadena único y el elemento de referencia tiene un href
atributo que hace referencia al mismo identificador.
<Group xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="id1" n1:GroupName=".NET" GroupNumber="ZDI=" CreationDate="2002-05-02" xmlns:n1="http:'www.cpandl.com">
<PosInt xsi:type="xsd:nonNegativeInteger">10000</PosInt>
<GroupVehicle href="#id2" />
</Group>
<Vehicle id="id2" n1:type="Vehicle" xmlns:n1="http://www.w3.org/2001/XMLSchema-instance">
<licenseNumber xmlns:q1="http://www.w3.org/2001/XMLSchema" n1:type="q1:string">1234</licenseNumber>
</Vehicle>
El UnreferencedObject evento se produce cuando hay una definición de tipo que se encuentra en el documento, pero ningún parámetro del cuerpo principal hace referencia a él. Cuando se produce el evento, puede recuperar el tipo XML del objeto sin referencia examinando la UnreferencedObject propiedad de la UnreferencedObjectEventArgs clase . La propiedad devuelve el UnreferencedId identificador XML del objeto.
El UnreferencedObject evento no debe confundirse con los UnknownElement eventos y UnknownNode , que se producen cuando no hay ningún miembro de clase que corresponda al tipo de elemento o nodo XML.