Scenario:
User submit XML using WebApi and I want to store it in SQL database in XML Column and retrieve later using Ajax/WebApi
Question:
How should I store it in the database? With or without declaration/encoding? Or should I add the encoding when returning the XML?
public async IActionResult Post([FromBody]XDocument xml)
{
var entity = new MyDocument();
entity.Xml = xml.ToString(); //??
db.Documents.Add(entity);
db.SaveChanges();
return Created();
}
public async Task<IActionResult> Get(int id)
{
var entity = db.Documents.Find(id);
return Content(entity.Xml, "application/xml"); //missing xml declaration
}
My Observations:
XDocument.ToString()
trims the XML declaration element:var xml = XDocument.Load(@"<?xml version=""1.0"" encoding=""utf-8""?> <Root><Child>Content</Child></Root>"); xml.ToString(); //<Root><Child>Content</Child></Root>
It's easy to include it, but I tought that maybe it's for a reason.
Edge browser does not display the XML when the response does not include xml declaration:
public IActionResult Get() { return Content("<Root><Child>Content</Child></Root>", "application/xml") }
When the response include xml declaration, but the encoding from the declaration does not match response encoding, it also fails with "Unable to switch encodings":
public IActionResult Get() { return Content(@"<?xml version=""1.0"" encoding=""utf-8""?> <Root><Child>Content</Child></Root>", "application/xml"); }
In order to make Edge browser to display the XML properly, I have to do folowing:
public IActionResult Get() { string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <Root><Child>Content</Child></Root>") var xmlDoc = XDocument.Parse(xml); return Content(xml, "application/xml", Encoding.GetEncoding(xmlDoc.Declaration.Encoding)); }
Since database also has some encoding, it's quite unclear to me, what is actually the right way.