How to: Customize SOAP Messages with XML Serialization

[Note: This topic is pre-release documentation and is subject to change in future releases. Blank topics are included as placeholders.]

The System.Web.Serialization namespace provides numerous attributes for controlling XML serialization that can be applied to the parameters and return values of Web service methods. This topic shows how to use the XmlElementAttribute attribute.

To specify the name of the XML element representing a parameter

  • Apply an XmlElement attribute to the parameter, which specifies the desired name for the element and, optionally, a namespace if the parameter formatting is set to Literal. If the parameter formatting is set to Encoded, apply a SoapElement attribute to the parameter.

    The following code example expects the element names that represent the parameters to be MyAddressElement, MyZipElement, and ReturnValueElement. It also expects the element name that represents the return value to be ReturnValueElement. The Web service method formatting in the sample is Document, which is the default for ASP.NET.

    <%@ WebService Language="C#" Class="SoapDocumentServiceSample" %>
     using System.Web.Services;
     using System.Web.Services.Protocols;
     using System.Xml.Serialization;
    public class SoapDocumentServiceSample  
      [ WebMethod ]
      [ return: XmlElement("ReturnValueElement",IsNullable=false)]
      public Address ValidateAddress(
        [XmlElement("MyAddressElement")] Address MyAddress,
        [XmlElement("MyZipElement")] bool useZipPlus4) 
        useZipPlus4 = true;    
        return new Address();

    <%@ WebService Language="VB" Class="SoapDocumentServiceSample" %>
     Imports System.Web.Services
     Imports System.Web.Services.Protocols
     Imports System.Xml.Serialization
    <WebService(Namespace := "")> _
    Public Class SoapDocumentServiceSample
      < WebMethod > _
      Public Function ValidateAddress( _
           <XmlElement("MyAddressElement")> MyAddress As Address, _
           <XmlElement("MyZipElement")> useZipPlus4 As Boolean)  
           As <XmlElement("ReturnValueElement",IsNullable :=false)> _
            useZipPlus4 = True 
         Return new Address()
      End Function
    End Class

    The Web service expects the following SOAP request. Notice the names of the elements match what is specified in the XmlElement attribute, as opposed to the parameter names.

    <?xml version="1.0" encoding="utf-8"?>
    <soap:Envelope xmlns:xsi="" xmlns:xsd="" xmlns:soap="">
        <ValidateAddress xmlns="">