Person person = GetPerson();
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add(string.Empty, string.Empty);
            XmlSerializer serializer = new XmlSerializer(typeof(Person));
            string personText = string.Empty;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream, new XmlWriterSettings() { Encoding = Encoding.UTF8 }))
                {
                    serializer.Serialize(xmlWriter, person, ns);
                    xmlWriter.Flush();
                    personText = Encoding.UTF8.GetString(memoryStream.ToArray());
                }
            }

            string path = @"D:\person.xml";
// Write method 1:
            File.WriteAllText(path, personText);

// Write method 2:
            using (StreamWriter streamWriter = new StreamWriter(path, false , Encoding.UTF8))
            {
                streamWriter.Write(personText);
            }

// Read the xml
            using (FileStream fileStream = new FileStream(path, FileMode.Open))
            {
                return XDocument.Load(XmlReader.Create(fileStream));
            }

当我在使用方法2编写之后读取XML时,在根级别得到的数据是无效的。1号线,位置1。但使用方法1时效果很好。
这是什么原因?任何指点都值得赞赏。

最佳答案

问题是StreamWriterXmlWriter都在添加字节顺序标记。
选项:
personText开始的bom字符串
对于new UTF8Encoding(false)
对于Encoding.UTF8
首先要避免转换成文本再转换回来:您已经在StreamWriter中获得了二进制数据,为什么不直接将其转储到磁盘?

10-06 01:58