Providing a WebMethod that returns XML as a string.

BabelFish picture BabelFish · Mar 17, 2010 · Viewed 12.7k times · Source

I keep reading how everyone states to return a XmlDocument when you want to return XML. Is there a way to return raw XML as a string? I have used many web services (written by others) that return a string which contains XML. If you return a XmlDocument how is that method consumed by users that are not on .Net?

What is the method to just return the raw XML as string without it having being wrapped with <string></string>?

Thanks!

Answer

Brian Scott picture Brian Scott · Mar 17, 2010

The first thing to understand with .Net webservices are that they used the SOAP protocol. This means that whatever types you return via your web method they will be serialised to XML. Therefore, every returned object will be an XML string passed back to the caller.

If you are still simply looking to return XML as an actual string value then create a server side method within your webservice as follows:

[WebMethod]
public string ReturnXMLString() {
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.LoadXml("<root><item>Hello World</item></root>");
    return xmlDoc.OuterXML;
}

If however you are trying to return actual XML to a caller then simply let .Net take care of serialising the XML as follows:

[WebMethod]
public XmlDocument ReturnXMLString() {
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.LoadXml("<root><item>Hello World</item></root>");
    return xmlDoc;
}

Lastly, if you are simply looking for a XML response without the SOAP protocol wrapping and serialising the response as XML then try a page response from a bespoke page:

void Page_Load(object sender, EventArgs e) {
XmlDocument xmlDoc= new XmlDocument();
xmlDoc.LoadXml("<root>Hello World</root>");
Response.ContentType ="text/xml";
xmlDoc.Save(Response.Output);