views:

305

answers:

1

I keep reading how everyone states to return 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 string and the string contains XML. If you return 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!

+2  A: 

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);
Brian Scott
I am okay with the soap and I am even okay with returning XmlDocument. I have two questions if I return an XmlDocument.1. how is the return value consumed by a language other then .Net? How would the return value look to ATL or Java? In .Net it would be consumed as XmlNode xml = MyService.MyCall();2. I see other services that return "string" and the string contains xml and the WSDL states soap was used. How are they accomplishing that? Are they doing Step 1 and by the time it gets to me it is XML again?Thanks!
BabelFish
It seems you question is really about how other languages consume your webservice. One thing to understand is that web services are generally SOAP based. This is a platform agnostic way to define data via XML. If you have a java client that reads a .Net web service then they will use XML as the common intermediate language without any dependency on the caller understanding the providers language implementation. That's why there's all the XML wrapping around the results, this is descriptive markup to represent one languages data type and value to another.
Brian Scott