Holy Diver
Holy Diver

Reputation: 103

XmlTextReader.Encoding is null after constructing from stream with encoding="utf-8"

According to the code documentation

    //
    // Summary:
    //     Gets the encoding of the document.
    //
    // Returns:
    //     The encoding value. If no encoding attribute exists, and there is no byte-order
    //     mark, this defaults to UTF-8.

so I would expect XmlTextReader.Encoding to never be null.

However, I find it is null when I run

var stream = new MemoryStream(Encoding.UTF8.GetBytes(
@"<?xml version=""1.0"" encoding=""utf-8""?>
...
</xml>"));
var xmlTextReader = new XmlTextReader(stream);

Is there some parameter I am missing in the constructor?

Upvotes: 0

Views: 166

Answers (1)

Durga Prasad
Durga Prasad

Reputation: 989

The xml posted in the question is not valid xml (...). I presume it denotes some more xml content.

Having said that, XMLTextReader cannot know the encoding type until unless it processes the content inside of it. In order to do so we an call the MoveToContent method. Once the method is executed, the encoding can be fetched from the reader.

var stream = new MemoryStream(Encoding.UTF8.GetBytes(
            @"<?xml version=""1.0"" encoding=""utf-8""?>
                <TestXmlNode>
            </xml>"));

var xmlTextReader = new XmlTextReader(stream);
xmlTextReader.MoveToContent();
var encoding = xmlTextReader.Encoding;

Upvotes: 1

Related Questions