How to serialize a list of lists with the type of

2019-08-21 12:34发布

Here is the code:

    [XmlRoot("Foo")]
    class Foo
    {
        [XmlElement("name")]
        string name;
    }

    [XmlRoot("FooContainer")]
    class FooContainer
    {
        [XmlElement("container")]
        List<List<Foo>> lst { get; set; }
    }

    XmlSerializer s = new XmlSerializer(typeof(FooContainer)); -->Can't pass through this.

Complains about not being able to implicitly cast it blah blah blah,

Anyone can tell what is wrong with this code?

2条回答
2楼-- · 2019-08-21 12:35

Foo and FooContainer need to be public. Other than that it worked fine for me. Had to flesh out the code a bit, but his works ...

class Program
{
    static void Main(string[] args)
    {
        XmlSerializer s = new XmlSerializer(typeof(FooContainer));

        var str = new StringWriter();
        var fc  = new FooContainer();

        var lst = new List<Foo>() { new Foo(), new Foo(), new Foo() };

        fc.lst.Add( lst );

        s.Serialize(str, fc);
    }
}

[XmlRoot("Foo")]    
public class Foo    {        
    [XmlElement("name")]        
    public string name = String.Empty;    }    

[XmlRoot("FooContainer")]    
public class FooContainer    {

    public List<List<Foo>> _lst = new List<List<Foo>>();
    public FooContainer()
    {

    }

    [XmlArrayItemAttribute()]
    public List<List<Foo>> lst { get { return _lst; } }
}
查看更多
贪生不怕死
3楼-- · 2019-08-21 12:45

I knew someone would mention public so i'll jump in here:

Yes, they need to be public, but that's not the only problem. Actually running a serialization doesn't work (gets the error described)

It doesn't like the List

[XmlRoot("Foo")]
public class Foo
{
    [XmlElement("name")]
    public string name;
}

[XmlRoot("FooContainer")]
public class FooContainer
{
    [XmlElement("container")]
    public List<SerializableList<Foo>> lst { get; set; }
}

[XmlRoot("list")]
public class SerializableList<T>
{
    [XmlElement("items")]
    public List<T> lst { get; set; }
}
查看更多
登录 后发表回答