Ali Aghareza posted a reply to my earlier messages with a really insightful example that presents one reason for ASP.NET to change the element name the type is serialized as: when the method returns two different instances of the same type.

However, all is not that rosy. If no element name is specified in the type's XmlRoot attribute, then ASP.NET will default to serializing the type with the Result element name if it is present as the method's return value; if the type is present as an out/ref argument, instead, ASP.NET will serialize it with the argument name as the element name. This ensures no clashes occur (well, mostly).

This behavior, however, breaks if you specify an element name in the types XmlRoot attribute, since the serialization will break (multiple elements with the same name introduced). This can be avoided, though, with careful use of the XmlElementAttribute in the method's signature.

Which brings me to another tricky little detail: Using the XmlElementAttribute without filling in the namespace argument can lead to unexpected results. Consider this new code:

<%@ WebService Language="C#" class="Weird2" %>
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml;
using System.Xml.Serialization;
[ XmlRoot(Namespace="/schemas/client") ]
public class Client
{
[ XmlAttribute("id") ]
public int ID;
[ XmlElement("name") ]
public string Name;
}
[ WebService(Namespace="/services/Weird2") ]
public class Weird2
{
[ WebMethod ]
[ return: XmlElement("client") ]
public Client GetClient(int id)
{
Client c = new Client();
c.ID = id;
c.Name = "Tomas";
return c;
}
}

This code, when invoked via SOAP, will return something like this:


xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">



string




Notice how the client element is now serialized outside the /schemas/client schema and instead is serialized in the WebService's default namespace. The reason I point this out as a potential problem is that since the Client type is serialized with an attribute, that attribute has just been left hanging, too (Yes, I'm aware of the special way attributes fit within XSD).

OK, maybe it's not a problem, but I sure as hell know this wasn't what I originally expected to happen :)


Tomas Restrepo

Software developer located in Colombia.