Define File Encoding When Saving Xml

Mar 3, 2011 at 9:22 AM

Hello there,

When I'm creating new xml, how can i define file encoding of new xml file?

For example;

my Xsd name is MyXsd.

var xml = new MyXsd();

//Filling xml stuff here.


This code is saving my xml with UTF8 file encoding. I want to define file encoding to iso-8859-1 or any other.

Thanks for your response.

Mar 3, 2011 at 10:38 AM


Use the other overload that writes to a TextWriter?

input.Save(new StreamWriter(File.Create("blah.xml"), Encoding.GetEncoding("CP819")));
I don't know if CP819 is the proper name for iso-8859-1 in .NET, but there all sorts of other names on the wiki page (ISO-8859-1: ISO_8859-1, iso-ir-100, csISOLatin1, latin1, l1, IBM819, CP819.) so one of them will work.




Mar 3, 2011 at 11:44 AM

Thank you very much. But in your code, File kept not accessible after Create. So i tried below and worked nice.


xml.Save(new StreamWriter(path, true, Encoding.GetEncoding("iso-8859-1")));

Mar 3, 2011 at 11:49 AM

Sounds a bit like XTypedElement wasn't closing the file handle off maybe?

You may have a problem because you've set the append to true:

"Determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file exists and append is true, the data is appended to the file. Otherwise, a new file is created."

This would create a nonsense xml file if the file already exists. May you should set it to false?


Mar 3, 2011 at 11:56 AM

no i mean the code that i wrote above worked. but you are right append true is for creating the file for the first time. should be false if you are updating.

Mar 3, 2011 at 1:02 PM

By default it indeed is not paying attention to encoding. This could be included if the XSD is in the same encoding as the XML should be, else you'll need some kind of overload.