【问题标题】:ASP.net Converting List<T> into XMLASP.net 将 List<T> 转换为 XML
【发布时间】:2016-08-16 16:32:50
【问题描述】:

我读过它,它看起来很简单,但我不知道为什么它每次都在 XmlSerializer 行上崩溃,我想知道为什么,因为人们用类似的东西回答了将列表转换为 xml 的问题它似乎对我不起作用!

代码如下:

类:

[Serializable()]
    public class Pogos
    {
        public string Pogo { get; set; }
        public DateTime Date { get; set; }
    }

每日pogo列表:

 public static List<Pogos> DailyPogos = null;

将 Daily Pogo 列表设置为 .xml 中的内容

 public static void SetDailyPogos()
    {
        string path = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/DailyPogos.xml");

        if (File.Exists(path))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Pogos>));

            StreamReader reader = new StreamReader(path);
            DailyPogos = (List<Pogos>)serializer.Deserialize(reader);
            reader.Close();

            foreach (var pogo in DailyPogos)
            {
                if (pogo.Date.Date != DateTime.Now.Date)
                    DailyPogos.Remove(pogo);
            }
        }
        else
            DailyPogos = new List<Pogos>();
    }

将 Daily Pogos (distinct) 保存在 .xml 中

public static void SaveDailyPogos(List<string> pogos)
    {
        foreach (var pogo in pogos)
        {
            var matches = DailyPogos.Where(e => e.Pogo.Contains(pogo));
            foreach ( var match in matches)
            {
                DailyPogos.Remove(match);
            }
            var pog = new Pogos();
            pog.Pogo = pogo;
            pog.Date = DateTime.Now;
            DailyPogos.Add(pog);
        }

        string path = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/DailyPogos.xml");

        //create the serialiser to create the xml
        XmlSerializer serialiser = new XmlSerializer(typeof(List<Pogos>));

        // Create the TextWriter for the serialiser to use
        TextWriter filestream = new StreamWriter(path);

        //write to the file
        serialiser.Serialize(filestream, DailyPogos);

        // Close the file
        filestream.Close();
    }

导致问题的线路(没有错误只是崩溃):

XmlSerializer serializer = new XmlSerializer(typeof(List<Pogos>));

编辑:在这种情况下我非常愚蠢,首先,我可以通过添加一个我不知道为什么我没有的 try catch 来观察异常。可能很累。 Exception 表示由于应用程序的保护级别而失败,通过将“public”添加到程序类来解决此问题。

【问题讨论】:

  • “没有错误只是崩溃”是什么意思?你是在调试器下运行这个吗?打开“中断所有异常”并编辑帖子以显示您获得的托管异常。
  • 需要xml样本
  • 能否分享完整的ToString() 异常输出,包括异常类型、回溯和消息?

标签: c# asp.net xml serialization


【解决方案1】:

我无法重现您声称看到的异常 - 鉴于 Pogo 类如您所说,那么 new XmlSerializer(typeof(List&lt;Pogos&gt;)) 不会引发异常。

你应该仔细检查这个类是public 并且在你的实际应用程序中有一个public parameterless constructor。如果没有,那么new XmlSerializer(typeof(List&lt;Pogos&gt;)) 确实会抛出异常。

话虽如此,在创建XmlSerializer 的调用附近有两个编码错误,即您正在修改DailyPogos 集合,同时使用foreach 语句枚举它。如documentation 中所述,这将引发异常:

IEnumerator.MoveNext Method ()

例外情况: InvalidOperationException:在创建枚举器后修改了集合。

要避免这些异常,您可以使用List.RemoveAll()。修改SetDailyPogos()如下:

XmlSerializer serializer = new XmlSerializer(typeof(List<Pogos>));
using (var reader = new StreamReader(path))
{
    DailyPogos = (List<Pogos>)serializer.Deserialize(reader);
}
var now = DateTime.Now;
DailyPogos.RemoveAll(p => p.Date.Date != now.Date);

还有SaveDailyPogos():

foreach (var pogo in pogos)
{
    DailyPogos.RemoveAll(p => p.Pogo.Contains(pogo));
    var pog = new Pogos();
    pog.Pogo = pogo;
    pog.Date = DateTime.Now;
    DailyPogos.Add(pog);
}

由于这些foreach 语句引发的异常发生在构造XmlSerializer 的调用附近,也许您弄错了异常的来源?

【讨论】:

  • 我得到这个异常:程序由于其保护级别而无法访问。只能处理公共类型。也感谢您的错误更正!
  • 无论如何,修复它非常感谢!确实是保护级别,我的Program类不公开……
【解决方案2】:

如果我理解正确,你有一个对象列表,你想序列化然后反序列化到\from XML.....

试试这个....

类.....

[Serializable()]
public class Pogos
{
    public string Pogo { get; set; }
    public DateTime Date { get; set; }
}

用途.....

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

代码.....

    static void Main(string[] args)
    {
        List<Pogos> dObjToSerialize = new List<Pogos>();

        dObjToSerialize.Add(new Pogos() { Date = DateTime.Now, Pogo = "Pogo 1" });
        dObjToSerialize.Add(new Pogos() { Date = DateTime.Now, Pogo = "Pogo 2" });
        dObjToSerialize.Add(new Pogos() { Date = DateTime.Now, Pogo = "Pogo 3" });
        dObjToSerialize.Add(new Pogos() { Date = DateTime.Now, Pogo = "Pogo 4" });

        Serialize(dObjToSerialize); // find you XML in a file called "xml.xml" in the build folder

        List<Pogos> dObjToDeserialize = Deserialize<List<Pogos>>();

    } // Put a break-point here and dObjToDeserialize will contain your objects from the "xml.xml"

    private static void Serialize<T>(T data)
    {

        // Use a file stream here.
        using (TextWriter WriteFileStream = new StreamWriter("xml.xml"))
        {
            // Construct a SoapFormatter and use it  
            // to serialize the data to the stream.
            XmlSerializer SerializerObj = new XmlSerializer(typeof(T));

            try
            {
                // Serialize EmployeeList to the file stream
                SerializerObj.Serialize(WriteFileStream, data);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Failed to serialize. Reason: {0}", ex.Message));
            }
        }
    }

    private static T Deserialize<T>() where T : new()
    {
        //List<Employee> EmployeeList2 = new List<Employee>();
        // Create an instance of T
        T ReturnListOfT = CreateInstance<T>();


        // Create a new file stream for reading the XML file
        using (FileStream ReadFileStream = new FileStream("xml.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            // Construct a XmlSerializer and use it  
            // to serialize the data from the stream.
            XmlSerializer SerializerObj = new XmlSerializer(typeof(T));
            try
            {
                // Deserialize the hashtable from the file
                ReturnListOfT = (T)SerializerObj.Deserialize(ReadFileStream);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Failed to serialize. Reason: {0}", ex.Message));
            }

        }
        // return the Deserialized data.
        return ReturnListOfT;
    }

    // function to create instance of T
    public static T CreateInstance<T>() where T : new()
    {
        return (T)Activator.CreateInstance(typeof(T));
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 2021-11-26
    • 2012-02-24
    • 2012-02-14
    • 1970-01-01
    相关资源
    最近更新 更多