在尝试回答另一个问题时,我正在将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字符串?
答案 0 :(得分:19)
短一点: - )
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
标头,因此它与您的代码不完全相同。要获得utf-8
标题,我们应该使用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());
}
}
答案 1 :(得分:1)
如果您要使用UTF8编码,就可以这样做
public class StringWriterUtf8 : System.IO.StringWriter
{
public override Encoding Encoding
{
get
{
return Encoding.UTF8;
}
}
}
然后像这样使用StringWriter的StringWriterUtf8读取
using (StringWriterUtf8 textWriter = new StringWriterUtf8())
{
serializer.Serialize(textWriter, tr, ns);
xmlText = textWriter.ToString();
}
答案 2 :(得分:0)
编写扩展方法或包装类/函数来封装代码段。
答案 3 :(得分:0)
您不需要MemoryStream
,只需使用StringWriter
:
var yourList = new List<int>() { 1, 2, 3 };
using (StringWriter sw = new StringWriter())
{
var xs = new XmlSerializer(yourList.GetType());
xs.Serialize(sw, yourList);
string xmlEncodedList = sw.ToString();
}