Easiest way to deserialize an array / sequence of objects from XML using C #?

I have a class Foo(assuming the correct directives using)

namespace Example
{
    [XmlRoot("foo")]
    class Foo
    {
        public Foo() {}

        [XmlElement("name")]
        public string Name;
    }
}

And the XmlSerializer can work with XML like this to create an object of type Foo

<foo>
    <name>BOSS</name>
</foo>

What is the minimal work I can do to get the XML document XmlSerializer to process this form,

<foos>
    <foo>
        <name>BOSS</name>
    </foo>
    <foo>
        <name>NOT A BOSS</name>
    </foo>
</foos>

and create an array of objects Foo?

EDIT:

How do I do this for one Foo:

var xr = new XmlTextReader("foo.xml");
var xs = new XmlSerializer(typeof(Foo));
var a = (Foo) xs.Deserialize(xr);

Potential example for Foo[]

var xr = new XmlTextReader("foos.xml");
var xs = new XmlSerializer(typeof(Foo[]));
var a = (Foo[]) xs.Deserialize(xr);
+5
source share
1 answer

As far as I know, for the simplest. Adding another Foos class and removing the xmlroot tag from the Foo class.

namespace Example
{
    [XmlRoot("foos")]    
    class Foos
    {
        public Foos() {}

        [XmlElement("foo")]
        public List<Foo> FooList {get; set;}
    }
}
+5
source

All Articles