3

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);

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

thanks i tried that but it didn't work either in my case. i am concatenating declaration to xml string and then returning it as content type xml.
so maybe try return File(stream, "text/xml"); instead?
Works thanks! I'm not sure why it wouldn't appear in Chrome but in IE
I'm glad I helped :) if you see the result in the IE and not in chrome it's a matter of the frontend code. Open developer tools in each web browser and check the console log.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.