CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

How to Return XmlDocument from ASP.Net Webservice and Consuming it
Submitted By Satheesh Babu B
On 2/5/2010 7:45:59 AM
Tags: ASP.Net,CodeDigest,Webservice  

How to Return XmlDocument from ASP.Net Webservice and Consuming it

When you try accessing a webservice that returns XmlDocument object, it will give you an error like below,

 

Cannot implicitly convert type 'System.Xml.XmlNode' to 'System.Xml.XmlDocument'. An explicit conversion exists (are you missing a cast?)

 

For example, if you have webservice like below,

WebService

[WebMethod]

    public XmlDocument GetEmployeeXml()

    {       

        XmlDocument _doc = new XmlDocument();

       

      //Your code goes here..

           

        return _doc;

    }

 

And, if you try consuming it by assigning the result to an XmlDocument object in the client you will get the above error.
Refer the below code,

Client - Consumer

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        localhost.WebService service = new localhost.WebService();

 

        XmlDocument _doc = new XmlDocument();

      

         _doc = service.GetEmployeeXml();

               

    }

}

 

You will get the above error because the actual XmlDocument will be marshaled to XmlNode in the client. So, in order to get back your XmlDocument object you need get the XmlNode object and construct back the XmlDocument object.
Refer below,

Client - Consumer

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        localhost.WebService service = new localhost.WebService();

 

        XmlDocument _doc = new XmlDocument();

      

        // _doc = service.GetEmployeeXml();

 

        XmlNode _node = service.GetEmployeeXml();

 

        _doc.AppendChild(_doc.ImportNode(_node,true));

 

        Response.Write(_doc.InnerText);

       

    }

}

 

Note
You have to send XmlNode as parameter if your webservice has XmlDocument object as parameter.

 

Reference
http://support.microsoft.com/kb/330600

 

Happy Coding!!

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..