Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I set the XDocument XDeclaration encoding type to iso-8859-1?

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>
like image 317
David Glenn Avatar asked Oct 09 '09 11:10

David Glenn


People also ask

How do I encode a document in XML?

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.

How to encode a document with an encoding other than UTF8?

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.

How to serialize LINQ to XML with the specified encoding?

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.


1 Answers

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.

like image 106
yfeldblum Avatar answered Sep 28 '22 10:09

yfeldblum