6

I am trying to write an XML response for my web service however I can't figure out how to make the declaration appear in the response.

My code is like so :

StringBuilder sBuilder = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sBuilder))
{
    writer.WriteStartDocument();
    writer.WriteStartElement("ReportResponse");
    Response.WriteXml(writer);
    writer.WriteEndElement();
    writer.WriteEndDocument();
}

var response = XElement.Parse(sBuilder.ToString());
return response;

Response is just a POCO for storing response data.

I am aware that the Save method includes the declaration and the ToString() method does not. I need to write my declaration back with ToString().

I really just want to return custom XML from my REST Service without casting my string 100 times to return valid XML. Is this even possible or am just spinning my wheels ?

Adam
  • 14,638
  • 2
  • 40
  • 63
BentOnCoding
  • 23,888
  • 10
  • 59
  • 92
  • 2
    Why not use a class that you then serialize to XML? – Maess Dec 27 '11 at 19:48
  • I could use this approach but i run into the same problem for different reasons. – BentOnCoding Dec 27 '11 at 19:56
  • Why are you returning an `XElement` and not an `XDocument` if you want the XML declaration? – Jacob Dec 27 '11 at 20:05
  • Also, why do you care about the declaration? If you just returned a response *object* and let the WCF serializer convert your data contract object into XML, you don't have to worry about the response XML being valid. If you really needed the declaration to appear and it does not by default, that would be something you'd configure at the service level, not on each method. – Jacob Dec 27 '11 at 20:08
  • we don't use default encoding and the xml header specifies that. – BentOnCoding Dec 27 '11 at 21:02
  • @Jacob XDocument does the same thing. – BentOnCoding Dec 27 '11 at 21:02

1 Answers1

1

If you want to include xml declaration, you can do it this way:

XDocument xdoc = XDocument.Parse(xmlString);
StringBuilder builder = new StringBuilder();
using (TextWriter writer = new StringWriter(builder))
{
    xdoc.Save(writer);
}
Console.WriteLine(builder);

Update: I've noticed, that StringWriter spoils encoding. So one more option is to do so:

string docWithDeclaration = xdoc.Declaration + xdoc.ToString();
IDeveloper
  • 1,171
  • 2
  • 9
  • 20