Webservice method return XmlDocument, Reference sees a XmlNode

David picture David · Apr 5, 2011 · Viewed 11.1k times · Source

I've faced a problem I can't solve that's why I beg you to help me! I'm working with a WebService and I'm trying to return a XmlDocument from a WebService method called GetSystemDocument which looks like :

[WebMethod(Description = "blabla")]
    public XmlDocument GetSystemDocument(string DocumentName)
    {
        return new XmlDocument();
    }

In the project where I reference this web service. Visual Studio tells me it cannot implicitily convert type 'System.Xml.XmlNode' to 'System.Xml.XmlDocument'.

If I look into the Reference.cs file(generated by Visual Studio) the code looks like :

/// <remarks/>
    [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://doc.cexp.ca/GetSystemDocument", RequestNamespace="http://doc.cexp.ca", ResponseNamespace="http://doc.cexp.ca", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
    public System.Xml.XmlNode GetSystemDocument(string DocumentName) {
        object[] results = this.Invoke("GetSystemDocument", new object[] {
                    DocumentName});
        return ((System.Xml.XmlNode)(results[0]));
    }

The problem is there. Instead of XmlNode we should see XmlDocument, If I edit it manually, It builds and everything works fine.

I've tried resetting IIS, update the reference, rebuild the web service. Someone has a solution?

Here is a Similar question which is unanswered.

Thanks a lot

Answer

Richard Schneider picture Richard Schneider · Apr 5, 2011

The result of a web method is included in the SOAP document which is a XML Document. So if you want to return XML from a web method you should return an XmlElement.

[WebMethod(Descrption = "foo")]
public XmlElement GetSystemDocument(string documentName)
{
   var doc = new XmlDocument();
   doc.LoadXml("<foo> <bar x="a"/> </foo>");
   return doc.DocumentElement;
}

Edit: Corrected the code to make sure that it compiles