How to include Declaration with XElement.ToString()
Asked Answered
M

1

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 ?

Mohenjodaro answered 27/12, 2011 at 19:44 Comment(6)
Why not use a class that you then serialize to XML?Riesman
I could use this approach but i run into the same problem for different reasons.Mohenjodaro
Why are you returning an XElement and not an XDocument if you want the XML declaration?Beeves
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.Beeves
we don't use default encoding and the xml header specifies that.Mohenjodaro
@Beeves XDocument does the same thing.Mohenjodaro
A
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();
Araxes answered 22/10, 2013 at 5:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.