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可以正常工作。
造成这种情况的原因是什么?任何指针都赞赏。
答案 0 :(得分:7)
问题在于StreamWriter
和 XmlWriter
都添加了字节顺序标记。
选项:
personText
串起来以new UTF8Encoding(false)
Encoding.UTF8
而不是StreamWriter
new UTF8Encoding(false)
Encoding.UTF8
而不是XmlWriter
MemoryStream
中获得了二进制数据,为什么不将 转储到磁盘?