Why doesn\'t the following code set the XML declaration encoding type? It always sets the encoding to utf-16 instead. Am I missing something very obvious?
v
I somehow can't find any working answer here, so here is an actual solution which will output the wanted encoding in the header:
private void CreateXml()
{
XmlTextWriter xmlwriter = new XmlTextWriter("c:\\test.xml", Encoding.GetEncoding("iso-8859-1"));
XDocument xdoc = new XDocument(
new XElement("Test")
);
xdoc.Save(xmlwriter);
xmlwriter.Close();
}
The reason why you are getting UTF-16 is that strings are encoded with UTF-16 in memory, and as long as you don't specify an encoding for the output of the XML, it will override the encoding in the XML header to match the actual encoding being used. Using an XmlTextWriter is one method of specifying a different encoding.
You can also let the XmlTextWriter write to a MemoryStream and then transform it back to string if you need to perform the whole operation in memory.