views:

563

answers:

2

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?

var xdoc = new XDocument(
  new XDeclaration("1.0", "iso-8859-1", null), 
  new XElement("root", "")
);

output:

<?xml version="1.0" encoding="utf-16"?>
<root></root>
+2  A: 

See the answer about specifying the TextWriter's encoding.

As an aside: ISO-8859-1 is a character-set, not an encoding. Unicode is also a character-set, but UTF-16 is an encoding of the Unicode character set into a sequence of bytes. You cannot specify a document's encoding as ISO-8859-1, just as you cannot specify a document's character-set as UTF-16. Note that Unicode is the native character-set and UTF-16 is the native Unicode encoding for both .NET and Java String classes and text-based or string-based operations.

Justice
Does that mean there is no way to specify an invalid encoding using XDocument? I'm submitting XML to a third party who require the incorrect declaration <?xml version="1.0" encoding="ISO-8859-1" ?>.
David G
I'm sure you can. What system out there conforms to proper usage, language, and spec?
Justice
+1  A: 

Check the encoding of the TextWriter you're using. See here.

najmeddine