Using ServiceModel.Web to return XML documents instead of Data Contracts

Published on May 5, 2007

So this may be heresy to some, but I really don't like returning data contracts.  If I understand correctly, Erik Johnson is saying pretty much the same thing here when he says "Please dont make us write objects to an HTTP context. We write data to an HTTP stream."

Anyway, if anyone else is trying to figure out how to return plain XML from a [WebGet] method, try something like this...

 

public XmlNode MyOperation() {

MemoryStream st = new MemoryStream();XmlTextWriter wr = new XmlTextWriter(st,Encoding.UTF8);wr.WriteStartDocument();wr.WriteStartElement("MyDocument");wr.WriteElementString("MyElement", "ElementValue");

wr.WriteEndElement();

wr.WriteEndDocument();wr.Flush();

XmlDocument doc = new XmlDocument();st.Position = 0;

doc.Load(st);return doc.DocumentElement;

}

It is probably far from the most efficient way of doing it, but it works and that is step one.  I'm not sure why XmlDocument does not work, but it doesn't appear to.