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>
If you want to indicate that a document is standalone, you must use this property. If you want to encode your document with an encoding other than utf-8, you can specify an encoding through the XDeclaration. Another approach for encoding a document is to specify the encoding on an XmlWriter that you pass to LINQ to XML for writing.
Sometimes you have to create an XML declaration for a document. If you want to indicate that a document is standalone, you must use this property. If you want to encode your document with an encoding other than utf-8, you can specify an encoding through the XDeclaration.
If you read an encoded document, then this property will be set to the code page name. If you set this property to a valid code page name, then when serializing, LINQ to XML will serialize with the specified encoding. Learn how to add content (elements, attributes, comments, processing instructions, text, and CDATA) to an XML tree.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With