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

前端 未结 3 1278
太阳男子
太阳男子 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:01

    I somehow can't find any working answer here, so here is an actual solution which will output the wanted encoding in the header:

        private void CreateXml()
        {       
            XmlTextWriter xmlwriter = new XmlTextWriter("c:\\test.xml", Encoding.GetEncoding("iso-8859-1"));        
    
            XDocument xdoc = new XDocument(
              new XElement("Test")
            );
    
            xdoc.Save(xmlwriter);
            xmlwriter.Close();
        }
    

    The reason why you are getting UTF-16 is that strings are encoded with UTF-16 in memory, and as long as you don't specify an encoding for the output of the XML, it will override the encoding in the XML header to match the actual encoding being used. Using an XmlTextWriter is one method of specifying a different encoding.

    You can also let the XmlTextWriter write to a MemoryStream and then transform it back to string if you need to perform the whole operation in memory.

提交回复
热议问题