我尝试将modelstate序列化为xml字符串。首先,我创建了一个模型状态字典,这个字典我尝试序列化。这是我使用的代码:
ModelStateDictionary dict = new ModelStateDictionary();
dict.Merge(ModelState);
XmlSerializer serializer = new XmlSerializer(dict.GetType());
using (StringWriter writer = new StringWriter()){
serializer.Serialize(writer, dict);
var r2 = writer.ToString();
}
创建了r2,但所有标签都填充了\ r \ n。我做错了什么?
答案 0 :(得分:0)
您可以使用XmlWriter并在设置中指定您不想保留空格和缩进:
XmlSerializer serializer = new XmlSerializer(dict.GetType());
var settings = new XmlWriterSettings { Indent = false };
using (var stream = new MemoryStream())
using (var writer = XmlWriter.Create(stream, settings))
{
serializer.Serialize(writer, dict);
string r2 = Encoding.UTF8.GetString(stream.ToArray());
}