How to best detect encoding in XML file?

后端 未结 2 1239
攒了一身酷
攒了一身酷 2020-12-19 04:14

To load XML files with arbitrary encoding I have the following code:

Encoding encoding;
using (var reader = new XmlTextReader(filepath))
{
    reader.MoveToC         


        
2条回答
  •  无人及你
    2020-12-19 04:46

    Another option, quite simple, is to use Linq to XML. The Load method automatically reads the encoding from the xml file. You can then get the encoder value by using the XDeclaration.Encoding property. An example from MSDN:

    // Create the document
    XDocument encodedDoc16 = new XDocument(
    new XDeclaration("1.0", "utf-16", "yes"),
    new XElement("Root", "Content")
    );
    encodedDoc16.Save("EncodedUtf16.xml");
    Console.WriteLine("Encoding is:{0}", encodedDoc16.Declaration.Encoding);
    Console.WriteLine();
    
    // Read the document
    XDocument newDoc16 = XDocument.Load("EncodedUtf16.xml");
    Console.WriteLine("Encoded document:");
    Console.WriteLine(File.ReadAllText("EncodedUtf16.xml"));
    Console.WriteLine();
    Console.WriteLine("Encoding of loaded document is:{0}", newDoc16.Declaration.Encoding);
    

    While this may not server the original poster, as he would have to refactor a lot of code, it is useful for someone who has to write new code for their project, or if they think that refactoring is worth it.

提交回复
热议问题