How do I serialize a list of lists with a custom object type?

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 indirectly throw him blah blah blah

Can anyone please tell what is wrong with this code?

0


a source to share


2 answers


Foo and FooContainer must be public. Also, it worked well for me. It was necessary to explain the code a little, but it 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; } }
}

      

+2


a source


I knew someone would have mentioned the public, so I'll go here:

Yes, they should be publicly available, but that's not the only problem. Actually doing serialization doesn't work (gets the described error)



He 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; }
}

      

+1


a source







All Articles