SoapTypeAttribute Clase
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í.
Controla el esquema generado por el XmlSerializer cuando una instancia de clase se serializa como XML codificado con SOAP.
public ref class SoapTypeAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Enum | System.AttributeTargets.Interface | System.AttributeTargets.Struct)]
public class SoapTypeAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Enum | System.AttributeTargets.Interface | System.AttributeTargets.Struct)>]
type SoapTypeAttribute = class
inherit Attribute
Public Class SoapTypeAttribute
Inherits Attribute
- Herencia
- Atributos
Ejemplos
En el ejemplo siguiente se serializa una clase denominada Group.
SoapTypeAttribute se aplica a la clase , con el TypeName establecido en "SoapGroupType".
SoapTypeAttribute También se invalida y cambia a TypeName "Team". Ambas versiones se serializan, lo que da como resultado dos archivos: SoapType.xml y SoapType2.xml.
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
// The SoapType is overridden when the
// SerializeOverride method is called.
[SoapType("SoapGroupType", "http://www.cohowinery.com")]
public class Group
{
public string GroupName;
public Employee[] Employees;
}
[SoapType("EmployeeType")]
public class Employee
{
public string Name;
}
public class Run
{
public static void Main()
{
Run test = new Run();
test.SerializeOriginal("SoapType.xml");
test.SerializeOverride("SoapType2.xml");
test.DeserializeObject("SoapType2.xml");
}
public void SerializeOriginal(string filename)
{
// Create an instance of the XmlSerializer class that
// can be used for serializing as a SOAP message.
XmlTypeMapping mapp =
(new SoapReflectionImporter()).ImportTypeMapping(typeof(Group));
XmlSerializer mySerializer = new XmlSerializer(mapp);
// Writing the file requires a TextWriter.
TextWriter writer = new StreamWriter(filename);
// Create an XML text writer.
XmlTextWriter xmlWriter = new XmlTextWriter(writer);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.Indentation = 2;
// Create an instance of the class that will be serialized.
Group myGroup = new Group();
// Set the object properties.
myGroup.GroupName = ".NET";
Employee e1 = new Employee();
e1.Name = "Pat";
myGroup.Employees=new Employee[]{e1};
// Write the root element.
xmlWriter.WriteStartElement("root");
// Serialize the class.
mySerializer.Serialize(xmlWriter, myGroup);
// Close the root tag.
xmlWriter.WriteEndElement();
// Close the XmlWriter.
xmlWriter.Close();
// Close the TextWriter.
writer.Close();
}
public void SerializeOverride(string filename)
{
// Create an instance of the XmlSerializer class that
// uses a SoapAttributeOverrides object.
XmlSerializer mySerializer = CreateOverrideSerializer();
// Writing the file requires a TextWriter.
TextWriter writer = new StreamWriter(filename);
// Create an XML text writer.
XmlTextWriter xmlWriter = new XmlTextWriter(writer);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.Indentation = 2;
// Create an instance of the class that will be serialized.
Group myGroup = new Group();
// Set the object properties.
myGroup.GroupName = ".NET";
Employee e1 = new Employee();
e1.Name = "Pat";
myGroup.Employees=new Employee[]{e1};
// Write the root element.
xmlWriter.WriteStartElement("root");
// Serialize the class.
mySerializer.Serialize(xmlWriter, myGroup);
// Close the root tag.
xmlWriter.WriteEndElement();
// Close the XmlWriter.
xmlWriter.Close();
// Close the TextWriter.
writer.Close();
}
private XmlSerializer CreateOverrideSerializer()
{
// Create and return an XmlSerializer instance used to
// override and create SOAP messages.
SoapAttributeOverrides mySoapAttributeOverrides =
new SoapAttributeOverrides();
SoapAttributes soapAtts = new SoapAttributes();
// Override the SoapTypeAttribute.
SoapTypeAttribute soapType = new SoapTypeAttribute();
soapType.TypeName = "Team";
soapType.IncludeInSchema = false;
soapType.Namespace = "http://www.microsoft.com";
soapAtts.SoapType = soapType;
mySoapAttributeOverrides.Add(typeof(Group),soapAtts);
// Create an XmlTypeMapping that is used to create an instance
// of the XmlSerializer. Then return the XmlSerializer object.
XmlTypeMapping myMapping = (new SoapReflectionImporter(
mySoapAttributeOverrides)).ImportTypeMapping(typeof(Group));
XmlSerializer ser = new XmlSerializer(myMapping);
return ser;
}
public void DeserializeObject(string filename)
{
// Create an instance of the XmlSerializer class.
XmlSerializer mySerializer = CreateOverrideSerializer();
// Reading the file requires a TextReader.
TextReader reader = new StreamReader(filename);
// Create an XML text reader.
XmlTextReader xmlReader = new XmlTextReader(reader);
xmlReader.ReadStartElement();
// Deserialize and cast the object.
Group myGroup = (Group) mySerializer.Deserialize(xmlReader);
xmlReader.ReadEndElement();
Console.WriteLine("The GroupName is " + myGroup.GroupName);
Console.WriteLine("Look at the SoapType.xml and SoapType2.xml " +
"files for the generated XML.");
// Close the readers.
xmlReader.Close();
reader.Close();
}
}
Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization
' The SoapType is overridden when the
' SerializeOverride method is called.
<SoapType("SoapGroupType", "http://www.cohowinery.com")> _
Public class Group
Public GroupName As String
Public Employees() As Employee
End Class
<SoapType("EmployeeType")> _
Public Class Employee
Public Name As String
End Class
Public class Run
Public Shared Sub Main()
Dim test As Run = New Run()
test.SerializeOriginal("SoapType.xml")
test.SerializeOverride("SoapType2.xml")
test.DeserializeObject("SoapType2.xml")
End Sub
Public Sub SerializeOriginal(filename As String )
' Create an instance of the XmlSerializer class that
' can be used for serializing as a SOAP message.
Dim mapp As XmlTypeMapping = _
(New SoapReflectionImporter()).ImportTypeMapping(GetType(Group))
Dim mySerializer As XmlSerializer = _
New XmlSerializer(mapp)
' Writing the file requires a TextWriter.
Dim writer As TextWriter = New StreamWriter(filename)
' Create an XML text writer.
Dim xmlWriter As XmlTextWriter = New XmlTextWriter(writer)
xmlWriter.Formatting = Formatting.Indented
xmlWriter.Indentation = 2
' Create an instance of the class that will be serialized.
Dim myGroup As Group = New Group()
' Set the object properties.
myGroup.GroupName = ".NET"
Dim e1 As Employee = New Employee()
e1.Name = "Pat"
myGroup.Employees=New Employee(){e1}
' Write the root element.
xmlWriter.WriteStartElement("root")
' Serialize the class.
mySerializer.Serialize(xmlWriter, myGroup)
' Close the root tag.
xmlWriter.WriteEndElement()
' Close the XmlWriter.
xmlWriter.Close()
' Close the TextWriter.
writer.Close()
End Sub
Public Sub SerializeOverride(filename As string )
' Create an instance of the XmlSerializer class that
' uses a SoapAttributeOverrides object.
Dim mySerializer As XmlSerializer = CreateOverrideSerializer()
' Writing the file requires a TextWriter.
Dim writer As TextWriter = New StreamWriter(filename)
' Create an XML text writer.
Dim xmlWriter As XmlTextWriter = New XmlTextWriter(writer)
xmlWriter.Formatting = Formatting.Indented
xmlWriter.Indentation = 2
' Create an instance of the class that will be serialized.
Dim myGroup As Group = New Group()
' Set the object properties.
myGroup.GroupName = ".NET"
Dim e1 As Employee = New Employee()
e1.Name = "Pat"
myGroup.Employees = New Employee(){e1}
' Write the root element.
xmlWriter.WriteStartElement("root")
' Serialize the class.
mySerializer.Serialize(xmlWriter, myGroup)
' Close the root tag.
xmlWriter.WriteEndElement()
' Close the XmlWriter.
xmlWriter.Close()
' Close the TextWriter.
writer.Close()
End Sub
Private Function CreateOverrideSerializer() As XmlSerializer
' Create and return an XmlSerializer instance used to
' override and create SOAP messages.
Dim mySoapAttributeOverrides As SoapAttributeOverrides = _
New SoapAttributeOverrides()
Dim soapAtts As SoapAttributes = New SoapAttributes()
' Override the SoapTypeAttribute.
Dim soapType As SoapTypeAttribute = New SoapTypeAttribute()
soapType.TypeName = "Team"
soapType.IncludeInSchema = false
soapType.Namespace = "http://www.microsoft.com"
soapAtts.SoapType = soapType
mySoapAttributeOverrides.Add(GetType(Group),soapAtts)
' Create an XmlTypeMapping that is used to create an instance
' of the XmlSerializer. Then return the XmlSerializer object.
Dim myMapping As XmlTypeMapping = (New SoapReflectionImporter( _
mySoapAttributeOverrides)).ImportTypeMapping(GetType(Group))
Dim ser As XmlSerializer = New XmlSerializer(myMapping)
return ser
End Function
Public Sub DeserializeObject(filename As String)
' Create an instance of the XmlSerializer class.
Dim mySerializer As XmlSerializer = CreateOverrideSerializer()
' Reading the file requires a TextReader.
Dim reader As TextReader = New StreamReader(filename)
' Create an XML text reader.
Dim xmlReader As XmlTextReader = New XmlTextReader(reader)
xmlReader.ReadStartElement()
' Deserialize and cast the object.
Dim myGroup As Group = CType(mySerializer.Deserialize(xmlReader), Group)
xmlReader.ReadEndElement()
Console.WriteLine("The GroupName is " + myGroup.GroupName)
Console.WriteLine("Look at the SoapType.xml and SoapType2.xml " + _
"files for the generated XML.")
' Close the readers.
xmlReader.Close()
reader.Close()
End Sub
End Class
Comentarios
La SoapTypeAttribute clase pertenece a una familia de atributos que controla cómo serializa XmlSerializer o deserializa un objeto como XML SOAP codificado. El XML resultante se ajusta a la sección 5 del documento World Wide Web Consortium, Protocolo simple de acceso a objetos (SOAP) 1.1. Para obtener una lista completa de atributos similares, vea Atributos que controlan la serialización SOAP codificada.
Para serializar un objeto como un mensaje SOAP codificado, construya XmlSerializer mediante un XmlTypeMapping objeto creado con el ImportTypeMapping método de la SoapReflectionImporter clase .
Solo SoapTypeAttribute se puede aplicar a las declaraciones de clase.
La IncludeInSchema propiedad determina si el tipo de elemento XML resultante se incluye en el documento esquema XML (.xsd) para la secuencia XML generada. Para ver el esquema, compile la clase en un archivo DLL. Pase el archivo resultante como argumento a la Herramienta de definición de esquemas XML (Xsd.exe). La herramienta genera el esquema XML para la secuencia XML generada cuando una instancia de la clase serializa la XmlSerializer clase .
Si se establece un espacio de nombres diferente, Xsd.exe escribir un archivo de esquema diferente (.xsd) para la secuencia XML generada cuando se serializa la clase.
Constructores
| Nombre | Description |
|---|---|
| SoapTypeAttribute() |
Inicializa una nueva instancia de la clase SoapTypeAttribute. |
| SoapTypeAttribute(String, String) |
Inicializa una nueva instancia de la SoapTypeAttribute clase y especifica el nombre y el espacio de nombres XML del tipo. |
| SoapTypeAttribute(String) |
Inicializa una nueva instancia de la SoapTypeAttribute clase y especifica el nombre del tipo XML. |
Propiedades
| Nombre | Description |
|---|---|
| IncludeInSchema |
Obtiene o establece un valor que indica si se debe incluir el tipo en documentos de esquema XML codificados con SOAP. |
| Namespace |
Obtiene o establece el espacio de nombres del tipo XML. |
| TypeId |
Cuando se implementa en una clase derivada, obtiene un identificador único para este Attribute. (Heredado de Attribute) |
| TypeName |
Obtiene o establece el nombre del tipo XML. |
Métodos
| Nombre | Description |
|---|---|
| Equals(Object) |
Devuelve un valor que indica si esta instancia es igual a un objeto especificado. (Heredado de Attribute) |
| GetHashCode() |
Devuelve el código hash de esta instancia. (Heredado de Attribute) |
| GetType() |
Obtiene el Type de la instancia actual. (Heredado de Object) |
| IsDefaultAttribute() |
Cuando se reemplaza en una clase derivada, indica si el valor de esta instancia es el valor predeterminado de la clase derivada. (Heredado de Attribute) |
| Match(Object) |
Cuando se reemplaza en una clase derivada, devuelve un valor que indica si esta instancia es igual a un objeto especificado. (Heredado de Attribute) |
| MemberwiseClone() |
Crea una copia superficial del Objectactual. (Heredado de Object) |
| ToString() |
Devuelve una cadena que representa el objeto actual. (Heredado de Object) |
Implementaciones de interfaz explícitas
| Nombre | Description |
|---|---|
| _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío. (Heredado de Attribute) |
| _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Recupera la información de tipo de un objeto, que se puede usar para obtener la información de tipo de una interfaz. (Heredado de Attribute) |
| _Attribute.GetTypeInfoCount(UInt32) |
Recupera el número de interfaces de información de tipo que proporciona un objeto (0 ó 1). (Heredado de Attribute) |
| _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Proporciona acceso a propiedades y métodos expuestos por un objeto . (Heredado de Attribute) |