Is it possible to return an XElement from a webservice (in C#/asp.net)?
Try a simple web service that returns an XElement:
[WebMethod]
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?
Thanks.
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.
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...
Return an XmlElement type, and just use this extension method to convert from XElement to XmlElement:
[System.Runtime.CompilerServices.Extension()]
public XmlElement ToXmlElement(XElement value)
{
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(value.ToString());
return xmlDoc.DocumentElement;
}
This seems to work well.
来源:https://stackoverflow.com/questions/349769/returning-an-xelement-from-a-web-service