开发者

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开发者_如何学JAVA 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);


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜