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

前端 未结 3 1241
太阳男子
太阳男子 2021-01-12 14:25

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?

v         


        
3条回答
  •  清酒与你
    2021-01-12 15:08

    As stated, the .NET XML/Stream writing implementation 'picks up' or interprets the encoding from somewhere other than the declared XML encoding. I have successfully tested a working solution, as described at the URL contained within the earlier Stackoverflow post

    XDocument xmlDoc = new XDocument(
            new XDeclaration("1.0", "utf-8", "no"), 
            new XElement("foo", "bar"));
    
    MemoryStream memstream = new MemoryStream();
    XmlTextWriter xmlwriter = new XmlTextWriter(memstream, new UTF8Encoding());
    
    //'Write' (save) XDocument XML to MemoryStream-backed XmlTextWriter instance
    xmlDoc.Save(xmlwriter);
    
    //Read back XML string from stream
    xmlwriter.Flush();    
    memstream.Seek(0, SeekOrigin.Begin);  //OR "stream.Position = 0"
    StreamReader streamreader = new StreamReader(memstream);
    string xml = streamreader.ReadToEnd();
    
    Console.WriteLine(xml);
    Console.WriteLine(reader.ReadToEnd());
    

    I hope this helps somebody.

    Cheers

提交回复
热议问题