Tag Archive for 'linq to xml'

ASP.NET Web Services & XElement Return Types

I’ve been a huge fan of LINQ to XML. So I have been trying to have a ASP.NET ASMX Web Service with several WebMethods return XElements. You cannot return the XDocument as it is not serializable. However, XElements are. But, in my experimentation, after having a few XElements returned, I receive an IllegalOperationException: Cannot use wildcards at the top level of a schema.

Here is an example of what I was trying to do:

using...
namespace WebServiceTest
{
    public class WebServiceTest : WebService
    {
        [WebMethod]
        public XElement OhHai()
        {
            return new XElement("OhHai");
        }

        [WebMethod]
        public XElement GetCheezburger()
        {
            return new XElement("ICanHasCheezburger");
        }

        [WebMethod]
        public XElement Errored()
        {
            return new XElement("KTHXBYE");
        }
    }
}

I have attempted this on three different computers with Visual Studio 2008. All behave correctly with one or two, but usually when adding the third, I get the exception. If I change the third to return something else, it works fine. Very strange. Obviously it’s some kind of bug on the .NET side of the world. I guess it still is best to return an XmlNode or even a string (but can sometimes be unpredictable)…

One last note for you beginners to LINQ to XML. When using XElements or XDocuments, you have really a lot at your disposal to convert this to something else. You can use the CreateReader or CreateWriter methods, ToString works, etc. My preferred method, however, is calling the WriteTo method. This allows the XML as it should be represented to be output flawlessly every time.