Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to deserialize an Array/Sequence of objects from XML with C#?

I have a class Foo (assume proper using directives)

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

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

And an XmlSerializer can deal with XML like this to produce an object of type Foo

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

What is the minimal amount of work I can do to make the XmlSerializer handle XML of this form,

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

and produce an array of Foo objects?

EDIT:

How I'm doing it for a single 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);
like image 316
Daniel Huckstep Avatar asked Mar 08 '11 23:03

Daniel Huckstep


1 Answers

To the best of my knowledge for the simplest. Adding another class Foos and removing the xmlroot tag from class Foo.

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

        [XmlElement("foo")]
        public List<Foo> FooList {get; set;}
    }
}
like image 103
Dylan Avatar answered Nov 06 '22 20:11

Dylan