Is it possible to return an XElement from a webservice (in C#/

Try a simple web service that returns an XElement:

public XElement DoItXElement()
  XElement xe = new XElement("hello",
     new XElement("message", "Hello World")

  return xe;

This compiles fine but if you try and run it you get

Cannot use wildcards at the top level of a schema.

I found this post implying that this is a bug in .net.

So... Can I return an XElement from a web service? If so, how?


+4  A: 

There appears to be an issue with how an XElement is serialized, check here...

You can try outing the XElement as a string or as the article suggests you could just use a class wrapper and place your XElement inside. If the point is to output the data in a universal format you'll be stuck with returning a string.

Being more prescriptive - it is the nature of XElement to be indeterminate until runtime. However the WebMethod needs a determinate root to begin deserialization. Wrapping is the way to go.
Unfortunately the external link is broken now.
Alexander Prokofyev
+2  A: 

I was trying to avoid the string!

I can return an XmlNode (created from the XElement), which gets me what I need - a slug of XML on the client. Thanks for that link - I shall investigate the XWrapper further...


Strangely enough, it seems that this only happens if you are trying to look at the "Discovery" part of the service - You can run the method without a problem...


It works just fine in Silverlight 4.

I'm still trying to figure out exactly when it doesn't work though.