Differences between XmlReader, StreamReader and StringReader in deserialization

1

I asked the following question here in stackoverflow link question .

During the deserialization, depending on the stream you use, an error can occur in the XML namespaces, depending on the question link.

Examples of the code that has the namespace error.

byte[] buffer = Convert.FromBase64String(base64);
        MemoryStream ms = new MemoryStream(buffer);
        XmlDocument doc = new XmlDocument();
        doc.Load(ms);

        XmlSerializer _xmlSerializer = new XmlSerializer(typeof(resNFe));

        XmlReader _reader = new XmlNodeReader(doc);

        //Não funciona  - xmlns:"" não esperado

        var _resNFe = (resNFe)xmlSerializer.Deserialize(_reader);

Code that works:

     // Funciona 100%
    var resnfe = new resNFe();
    string caminho = @"C:\home160604301024000131550010001971591190360567.xml";
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(resNFe));
    StreamReader reader = new StreamReader(caminho);
    resnfe = (resNFe)xmlSerializer.Deserialize(reader);
    reader.Close();

This also works:

public static T LoadFromXMLString<T>(string xmlText)
{
var stringReader = new System.IO.StringReader(xmlText);
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(stringReader);
}

Remembering that the same XML and the same serialized class are being used.

Does anyone know why this namespace error depends on the stream used?

XmlDocument:

<resNFe xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" versao="1.00" xmlns="http://www.portalfiscal.inf.br/nfe">
<chNFe>5616516516516516816165165156</chNFe>
<CNPJ>12345678654231</CNPJ>
<xNome>bla bla bla</xNome>
<IE>651651654</IE>
<dhEmi>2016-06-28T09:00:04-03:00</dhEmi>
<tpNF>1</tpNF>
<vNF>10049.69</vNF>
<digVal>asdasdasdzc5asr41fa564s</digVal>
<dhRecbto>2016-06-28T09:16:34-03:00</dhRecbto>
<nProt>3531351313235151</nProt>
<cSitNFe>1</cSitNFe>
</resNFe>
    
asked by anonymous 19.08.2016 / 15:49

1 answer

1

It seems to be a bug in the implementation of XmlNodeReader that they did not want to solve. This Page Here (which, by the way, leads to this answer here ) has more details about the bug.

On the page itself, one contributor said it was decided not to fix the bug. So it's best to use StreamReader or StringReader .

EDIT: Well, I think I can better explain what happens. In XmlNodeReader , the code that will compare the namespaces looks like this here:

(object) ((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_namespace))

It means that it does a comparison of objects (which is done by reference), not a comparison of strings (which is done by value). As an object is only equal to itself, this comparison always gives problem.

    
20.08.2016 / 17:36