不,您可以使用StringWriter
摆脱中间体MemoryStream
。但是,要强制将其转换为XML,您需要使用StringWriter
覆盖Encoding
属性的:
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding => Encoding.UTF8;
}
或者,如果您尚未使用C#6:
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding { get { return Encoding.UTF8; } }
}
然后:
var serializer = new XmlSerializer(typeof(SomeSerializableObject));
string utf8;
using (StringWriter writer = new Utf8StringWriter())
{
serializer.Serialize(writer, entry);
utf8 = writer.ToString();
}
显然,您可以使它Utf8StringWriter
成为一个更通用的类,该类可以接受其构造函数中的任何编码-但以我的经验,UTF-8是迄今为止最常用的“自定义”编码StringWriter
:)
现在,就像乔恩·汉纳(Jon Hanna)所说的那样,内部仍将是UTF-16,但是大概您将在某个时候将其传递给其他东西,以将其转换为二进制数据...在那时,您可以使用上面的字符串,将其转换为UTF-8字节,一切都会很好-因为XML声明将指定“ utf-8”作为编码。
编辑:一个简短但完整的示例,以显示此工作:
using System;
using System.Text;
using System.IO;
using System.Xml.Serialization;
public class Test
{
public int X { get; set; }
static void Main()
{
Test t = new Test();
var serializer = new XmlSerializer(typeof(Test));
string utf8;
using (StringWriter writer = new Utf8StringWriter())
{
serializer.Serialize(writer, t);
utf8 = writer.ToString();
}
Console.WriteLine(utf8);
}
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding => Encoding.UTF8;
}
}
结果:
<?xml version="1.0" encoding="utf-8"?>
<Test xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<X>0</X>
</Test>
我相信,请注意声明的“ utf-8”编码,这是我们想要的。