Serialización XML con servicios Web XMLXML Serialization with XML Web Services
La serialización XML es el mecanismo de transporte subyacente utilizado en la arquitectura de los servicios Web XML, realizada por la clase XmlSerializer.XML serialization is the underlying transport mechanism used in the XML Web services architecture, performed by the XmlSerializer class. Para controlar el XML generado por un servicio web XML, puede aplicar los atributos de Atributos que controlan la serialización XML y Atributos que controlan la serialización SOAP codificada a las clases, los valores devueltos, los parámetros y los campos de un archivo usados para crear un servicio web XML (.asmx).To control the XML generated by an XML Web service, you can apply the attributes listed in both Attributes That Control XML Serialization and Attributes That Control Encoded SOAP Serialization to the classes, return values, parameters, and fields of a file used to create an XML Web service (.asmx). Para más información sobre cómo crear un servicio web XML, vea Servicios web XML con ASP.NET.For more information about creating an XML Web service, see XML Web Services Using ASP.NET.
Estilos literales y codificadosLiteral and Encoded Styles
Se puede aplicar formato al XML generado por un servicio web XML de dos maneras distintas, estilo literal o codificado, como se explica en Personalizar el formato de mensajes SOAP.The XML generated by an XML Web service can be formatted in either one of two ways, either literal or encoded, as explained in Customizing SOAP Message Formatting. Hay, por consiguiente, dos conjuntos de atributos que controlan la serialización XML.Therefore there are two sets of attributes that control XML serialization. Los atributos que se mencionan en Atributos que controlan la serialización XML están diseñados para controlar el XML de estilo literal.The attributes listed in Attributes That Control XML Serialization are designed to control literal style XML. Los atributos mencionados en Atributos que controlan la serialización SOAP codificada controlan el estilo codificado.The attributes listed in Attributes That Control Encoded SOAP Serialization control the encoded style. Aplicando selectivamente estos atributos, puede entallar una aplicación para devolver uno o ambos estilos.By selectively applying these attributes, you can tailor an application to return either, or both styles. Además, estos atributos se pueden aplicar (según corresponda) a los valores devueltos y parámetros.Furthermore, these attributes can be applied (as appropriate) to return values and parameters.
Ejemplo de utilizar ambos estilosExample of Using Both Styles
Al estar creando un servicio Web XML, puede utilizar ambos conjuntos de atributos en los métodos.When you're creating an XML Web service, you can use both sets of attributes on the methods. En el ejemplo de código siguiente, la clase denominada MyService
contiene dos métodos de servicios Web XML, MyLiteralMethod
y MyEncodedMethod
.In the following code example, the class named MyService
contains two XML Web service methods, MyLiteralMethod
and MyEncodedMethod
. Ambos métodos realizan la misma función: devolviendo una instancia de la clase Order
.Both methods perform the same function: returning an instance of the Order
class. En la clase Order
, los atributos XmlTypeAttribute y SoapTypeAttribute se aplican al campo OrderID
y ambos tienen la propiedad ElementName
establecida en valores diferentes.In the Order
class, the XmlTypeAttribute and the SoapTypeAttribute attributes are both applied to the OrderID
field, and both attributes have their ElementName
property set to different values.
Para ejecutar el ejemplo, pegue el código en un archivo con una extensión .asmx y coloque el archivo en un directorio virtual administrado por Internet Information Services (IIS).To run the example, paste the code into a file with an .asmx extension, and place the file into a virtual directory managed by Internet Information Services (IIS). De un examinador de HTML, como Internet Explorer, escriba el nombre del equipo, directorio virtual y archivo.From an HTML browser, such as Internet Explorer, type the name of the computer, virtual directory, and file.
<%@ WebService Language="VB" Class="MyService" %>
Imports System
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Xml.Serialization
Public Class Order
' Both types of attributes can be applied. Depending on which type
' the method used, either one will affect the call.
<SoapElement(ElementName:= "EncodedOrderID"), _
XmlElement(ElementName:= "LiteralOrderID")> _
public OrderID As String
End Class
Public Class MyService
<WebMethod, SoapDocumentMethod> _
public Function MyLiteralMethod() As Order
Dim myOrder As Order = New Order()
return myOrder
End Function
<WebMethod, SoapRpcMethod> _
public Function MyEncodedMethod() As Order
Dim myOrder As Order = New Order()
return myOrder
End Function
End Class
<%@ WebService Language="C#" Class="MyService" %>
using System;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Serialization;
public class Order {
// Both types of attributes can be applied. Depending on which type
// the method used, either one will affect the call.
[SoapElement(ElementName = "EncodedOrderID")]
[XmlElement(ElementName = "LiteralOrderID")]
public String OrderID;
}
public class MyService {
[WebMethod][SoapDocumentMethod]
public Order MyLiteralMethod(){
Order myOrder = new Order();
return myOrder;
}
[WebMethod][SoapRpcMethod]
public Order MyEncodedMethod(){
Order myOrder = new Order();
return myOrder;
}
}
En el ejemplo de código siguiente se llama a MyLiteralMethod
.The following code example calls MyLiteralMethod
. El nombre de elemento se cambia a "LiteralOrderID."The element name is changed to "LiteralOrderID".
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<MyLiteralMethodResponse xmlns="http://tempuri.org/">
<MyLiteralMethodResult>
<LiteralOrderID>string</LiteralOrderID>
</MyLiteralMethodResult>
</MyLiteralMethodResponse>
</soap:Body>
</soap:Envelope>
En el ejemplo de código siguiente se llama a MyEncodedMethod
.The following code example calls MyEncodedMethod
. El nombre de elemento es "EncodedOrderID."The element name is "EncodedOrderID".
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://tempuri.org/" xmlns:types="http://tempuri.org/encodedTypes" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<tns:MyEncodedMethodResponse>
<MyEncodedMethodResult href="#id1" />
</tns:MyEncodedMethodResponse>
<types:Order id="id1" xsi:type="types:Order">
<EncodedOrderID xsi:type="xsd:string">string</EncodedOrderID>
</types:Order>
</soap:Body>
</soap:Envelope>
Aplicar los atributos a los valores de devoluciónApplying Attributes to Return Values
También puede aplicar los atributos a los valores devueltos para controlar el espacio de nombres, nombre de elemento, etc.You can also apply attributes to return values to control the namespace, element name, and so forth. En el ejemplo de código siguiente se aplica el atributo XmlElementAttribute
para devolver valores del método MyLiteralMethod
.The following code example applies the XmlElementAttribute
attribute to the return value of the MyLiteralMethod
method. Hacer esto le permite controlar el espacio de nombres y nombre de elemento.Doing so allows you to control the namespace and element name.
<WebMethod, SoapDocumentMethod> _
public Function MyLiteralMethod() As _
<XmlElement(Namespace:="http://www.cohowinery.com", _
ElementName:= "BookOrder")> _
Order
Dim myOrder As Order = New Order()
return myOrder
End Function
[return: XmlElement(Namespace = "http://www.cohowinery.com",
ElementName = "BookOrder")]
[WebMethod][SoapDocumentMethod]
public Order MyLiteralMethod(){
Order myOrder = new Order();
return myOrder;
}
Cuando se invoca, el código devuelve XML que se parece a lo siguiente.When invoked, the code returns XML that resembles the following.
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<MyLiteralMethodResponse xmlns="http://tempuri.org/">
<BookOrder xmlns="http://www.cohowinery.com">
<LiteralOrderID>string</LiteralOrderID>
</BookOrder>
</MyLiteralMethodResponse>
</soap:Body>
</soap:Envelope>
Atributos aplicados a parámetrosAttributes Applied to Parameters
También puede aplicar los atributos a los parámetros para especificar el espacio de nombres, nombre de elemento etc.You can also apply attributes to parameters to specify namespace, element name and so forth. El ejemplo de código siguiente agrega un parámetro al método MyLiteralMethodResponse
y aplica el atributo XmlAttributeAttribute
al parámetro.The following code example adds a parameter to the MyLiteralMethodResponse
method, and applies the XmlAttributeAttribute
attribute to the parameter. El nombre de elemento y espacio de nombres están establecidos para el parámetro.The element name and namespace are both set for the parameter.
<WebMethod, SoapDocumentMethod> _
public Function MyLiteralMethod(<XmlElement _
("MyOrderID", Namespace:="http://www.microsoft.com")>ID As String) As _
<XmlElement(Namespace:="http://www.cohowinery.com", _
ElementName:= "BookOrder")> _
Order
Dim myOrder As Order = New Order()
myOrder.OrderID = ID
return myOrder
End Function
[return: XmlElement(Namespace = "http://www.cohowinery.com",
ElementName = "BookOrder")]
[WebMethod][SoapDocumentMethod]
public Order MyLiteralMethod([XmlElement("MyOrderID",
Namespace="http://www.microsoft.com")] string ID){
Order myOrder = new Order();
myOrder.OrderID = ID;
return myOrder;
}
La solicitud SOAP debería tener un aspecto similar al siguiente.The SOAP request would resemble the following.
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<MyLiteralMethod xmlns="http://tempuri.org/">
<MyOrderID xmlns="http://www.microsoft.com">string</MyOrderID>
</MyLiteralMethod>
</soap:Body>
</soap:Envelope>
Aplicar los atributos a las clasesApplying Attributes to Classes
Si necesita controlar el espacio de nombres de elementos que ponen en correlación a las clases, puede aplicar XmlTypeAttribute
, XmlRootAttribute
y SoapTypeAttribute
, según corresponda.If you need to control the namespace of elements that correlate to classes, you can apply XmlTypeAttribute
, XmlRootAttribute
, and SoapTypeAttribute
, as appropriate. En el siguiente ejemplo de código se aplican los tres a la clase Order
.The following code example applies all three to the Order
class.
<XmlType("BigBookService"), _
SoapType("SoapBookService"), _
XmlRoot("BookOrderForm")> _
Public Class Order
' Both types of attributes can be applied. Depending on which
' the method used, either one will affect the call.
<SoapElement(ElementName:= "EncodedOrderID"), _
XmlElement(ElementName:= "LiteralOrderID")> _
public OrderID As String
End Class
[XmlType("BigBooksService", Namespace = "http://www.cpandl.com")]
[SoapType("SoapBookService")]
[XmlRoot("BookOrderForm")]
public class Order {
// Both types of attributes can be applied. Depending on which
// the method used, either one will affect the call.
[SoapElement(ElementName = "EncodedOrderID")]
[XmlElement(ElementName = "LiteralOrderID")]
public String OrderID;
}
Se pueden ver los resultados de aplicar XmlTypeAttribute
y SoapTypeAttribute
al examinar la descripción del servicio, como se muestra en el ejemplo de código siguiente.The results of applying the XmlTypeAttribute
and SoapTypeAttribute
can be seen when you examine the service description, as shown in the following code example.
<s:element name="BookOrderForm" type="s0:BigBookService" />
<s:complexType name="BigBookService">
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="LiteralOrderID" type="s:string" />
</s:sequence>
<s:schema targetNamespace="http://tempuri.org/encodedTypes">
<s:complexType name="SoapBookService">
<s:sequence>
<s:element minOccurs="1" maxOccurs="1" name="EncodedOrderID" type="s:string" />
</s:sequence>
</s:complexType>
</s:schema>
</s:complexType>
El efecto de XmlRootAttribute
también se puede ver en el Http GET y resultados de Http POST, como sigue.The effect of the XmlRootAttribute
can also be seen in the HTTP GET and HTTP POST results, as follows.
<?xml version="1.0" encoding="utf-8"?>
<BookOrderForm xmlns="http://tempuri.org/">
<LiteralOrderID>string</LiteralOrderID>
</BookOrderForm>
Vea tambiénSee also
- Serialización SOAP y XMLXML and SOAP Serialization
- Atributos que controlan la serialización SOAP codificadaAttributes That Control Encoded SOAP Serialization
- Cómo: Serializar un objeto como secuencia XML con codificación SOAPHow to: Serialize an Object as a SOAP-Encoded XML Stream
- Cómo: invalidar la serialización XML SOAP codificadaHow to: Override Encoded SOAP XML Serialization
- Introducción a la serialización XMLIntroducing XML Serialization
- Cómo: Serialización de un objetoHow to: Serialize an Object
- Cómo: Deserialización de un objetoHow to: Deserialize an Object