gpt4 book ai didi

c# - TextWriter 序列化为 UTF-8 字符串

转载 作者:太空狗 更新时间:2023-10-29 21:26:54 25 4
gpt4 key购买 nike

我使用TextWriter来序列化,因为它很容易在字符串序列化和文件序列化之间切换:

序列化为字符串;

TextWriter stringWriter = new StringWriter();
XmlSerializer serializer = XmlSerializer(typeof(ObjectType))
serializer.Serialize(stringWriter , objetToSerialize)
return stringWriter.ToString();

序列化到文件;

TextWriter fileWriter = new StreamWriter(targetXMLFileName, true, Encoding.UTF8);
XmlSerializer serializer = XmlSerializer(typeof(ObjectType))
serializer.Serialize(fileWriter , objetToSerialize)
fileWriter.Close();

我的问题是,当序列化为字符串时,它会创建一个 UTF-16 ("?xml version="1.0"encoding="utf-16"?"),并且 TestWriter 编码属性为 ReadOnly

我试过:

var memoryStream = new MemoryStream();
TextWriter stringWriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);
XmlSerializer serializer = XmlSerializer(typeof(ObjectType))
serializer.Serialize(stringWriter , objetToSerialize)
return stringWriter.ToString();

但它不起作用。它生成此字符串而不是 XML 文档:“System.IO.StreamWriter” O_o

如何将 TextWriter 初始化为 UTF-8 编码

最佳答案

代替 stringWriter.ToString,使用

string xml = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
return xml;

这会将您写入的内存流转换为 header 中带有 utf-8 的可打印 XML。

关于c# - TextWriter 序列化为 UTF-8 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35071369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com