将Modelstate序列化为XML asp.net mvc

时间:2011-10-30 09:19:34

标签: c# asp.net-mvc-3 serialization

我尝试将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。我做错了什么?

1 个答案:

答案 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());
}