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:
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);
Maybe try this:
public IActionResult Index()
{
// you need to convert your xml to string
var xmlString = "xml content..";
return this.Content(xmlString, "text/xml");
}
See https://learn.microsoft.com/en-us/previous-versions/aspnet/web-frameworks/dd492713%28v%3dvs.100%29
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With