gpt4 book ai didi

c# - 如何更改 TextWriter 对象中的编码?

转载 作者:数据小太阳 更新时间:2023-10-29 01:46:28 25 4
gpt4 key购买 nike

我有 xml,我在另一个 resurse 中通过 API 发送了它。我通过 XDocument 创建它:

XDocument xDoc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Entity",new XAttribute("Type", "attribute1"),
new XElement("Fields",...

当我把它放在请求中时,它没有声明就发送了。所以我接下来要做的是:

StringBuilder builder = new StringBuilder();
TextWriter writer = new StringWriter(builder);

using (writer)
{
xDoc.Save(writer);
}

但现在 TextWriter 将 xml 中的编码更改为 utf-16。我需要在 utf-8 上再次更改它。

最佳答案

这看起来很奇怪,但是如果你想输出到 xml 中使用 utf-8 编码的 string,你似乎必须子类化 StringWriter

public class Program
{
public static void Main(string[] args)
{
XDocument xDoc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Entity",new XAttribute("Type", "attribute1")));

StringBuilder builder = new StringBuilder();
using (TextWriter writer = new EncodingStringWriter(builder, Encoding.UTF8))
{
xDoc.Save(writer);
}

Console.WriteLine(builder.ToString());
}
}

public class EncodingStringWriter : StringWriter
{
private readonly Encoding _encoding;

public EncodingStringWriter(StringBuilder builder, Encoding encoding) : base(builder)
{
_encoding = encoding;
}

public override Encoding Encoding
{
get { return _encoding; }
}
}

关于c# - 如何更改 TextWriter 对象中的编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14743310/

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