I'm unable to attach a xml declaration while returning xml using Action Result. I can see it being included while debugging till line at which it returns xml in below code but doesn't not show up on the web.
What I am doing currently:
- Getting Xml from Sql Server using XML PATH.
Returning xml string using
XML Reader:public XmlDocumentResult XmlData() { String s = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "\n" + this.GetData(); byte[] encodedString = Encoding.UTF8.GetBytes(s); MemoryStream ms = new MemoryStream(encodedString); ms.Flush(); ms.Position = 0; XmlDocument doc = new XmlDocument(); doc.Load(ms); return new XmlDocumentResult { XmlDocument = doc }; } public class XmlDocumentResult : ContentResult { public XmlDocument XmlDocument { get; set; } public override void ExecuteResult(ControllerContext context) { if (XmlDocument == null) return; Content = XmlDocument.OuterXml; ContentType = "text/xml"; base.ExecuteResult(context); } }
I have tried following code snippets from Stackoverflow:
XmlDeclaration xmldecl;
xmldecl = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDocument.DocumentElement;
xmlDocument.InsertBefore(xmldecl, root);
XmlNode docNode = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
xml.AppendChild(docNode);