在尝试回答另一个问题时,我正在将C#对象序列化为XML字符串。令人惊讶的是,这很困难。这是我能想到的最短的代码片段:
var yourList = new List<int>() { 1, 2, 3 };
var ms = new MemoryStream();
var xtw = new XmlTextWriter(ms, Encoding.UTF8);
var xs = new XmlSerializer(yourList.GetType());
xs.Serialize(xtw, yourList);
var encoding = new UTF8Encoding();
string xmlEncodedList = encoding.GetString(ms.GetBuffer());
结果还可以:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfInt
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<int>1</int>
<int>2</int>
<int>3</int>
</ArrayOfInt>
但是摘要比我想象的要复杂。我不敢相信您必须了解有关此简单任务的编码和MemoryStream。
有没有更短的方法将对象序列化为XML字符串?
最佳答案
短一点:-)
var yourList = new List<int>() { 1, 2, 3 };
using (var writer = new StringWriter())
{
new XmlSerializer(yourList.GetType()).Serialize(writer, yourList);
var xmlEncodedList = writer.GetStringBuilder().ToString();
}
尽管以前的方法存在缺陷,但值得指出。当我们使用StringWriter时,它将生成
utf-16
header ,因此它与您的代码不完全相同。要获取utf-8
header ,我们应该使用MemoryStream和XmlWriter,这是另一行代码:var yourList = new List<int>() { 1, 2, 3 };
using (var stream = new MemoryStream())
{
using (var writer = XmlWriter.Create(stream))
{
new XmlSerializer(yourList.GetType()).Serialize(writer, yourList);
var xmlEncodedList = Encoding.UTF8.GetString(stream.ToArray());
}
}