qxn
qxn

Reputation: 17584

Getting byte array from XML string with encoding

I have XML content in a string that defines its encoding in its declaration. I want to get a byte array from that string and download it to a client browser.

The following works, but I'm not that experienced with encoding and am wondering will I cause something to blow up if I do it this way?

Basically, I'm getting the encoding from the declaration, and using that encoding to convert the XML string to a byte array. Is that how it should work?

var xdoc = XDocument.Parse(xmlString);
var encoding = System.Text.Encoding.GetEncoding(xdoc.Document.Declaration.Encoding);

var encoded = encoding.GetBytes(xmlString);

Response.AppendHeader("Content-Disposition", "attachment; filename=" + xmlData.FileName);
return File(encoded, "text/plain");

Upvotes: 2

Views: 3825

Answers (1)

Dave Kerr
Dave Kerr

Reputation: 5297

You should put an exception handler around GetEncoding - it'll throw if it doesn't recognise the encoding name. Otherwise you're fine.

Upvotes: 1

Related Questions