Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return Xml with declaration using an ActionResult in ASP.NET MVC?

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:

  1. Getting Xml from Sql Server using XML PATH.
  2. 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);
like image 685
Eicv Avatar asked Dec 08 '25 10:12

Eicv


1 Answers

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

like image 85
GoldenAge Avatar answered Dec 09 '25 22:12

GoldenAge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!