简体   繁体   English

将Modelstate序列化为XML asp.net MVC

[英]Serialize Modelstate to XML asp.net mvc

Im trying the serialize the modelstate to an xml string. 我正在尝试将modelstate序列化为xml字符串。 First I create a modelstate dictionary and this dictionary I try to serialize. 首先,我创建一个modelstate字典,然后尝试对该字典进行序列化。 This is the code I use: 这是我使用的代码:

 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 is created, but all tags are filled with \\r\\n. r2已创建,但所有标签都用\\ r \\ n填充。 What am I doing wrong? 我究竟做错了什么?

You could use a XmlWriter and specify in the settings that you don't want to keep whitespaces and indentation: 您可以使用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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM