[英]Simplest way to deserialize an Array/Sequence of objects from XML with C#?
I have a class Foo
(assume proper using
directives) 我有一个
Foo
类(假设using
指令正确)
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
XmlSerializer可以像这样处理XML,以产生
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, 使XmlSerializer处理这种形式的XML所需的最小工作量是什么,
<foos>
<foo>
<name>BOSS</name>
</foo>
<foo>
<name>NOT A BOSS</name>
</foo>
</foos>
and produce an array of Foo
objects? 并产生一个
Foo
对象数组?
EDIT: 编辑:
How I'm doing it for a single Foo
: 我如何针对单个
Foo
:
var xr = new XmlTextReader("foo.xml");
var xs = new XmlSerializer(typeof(Foo));
var a = (Foo) xs.Deserialize(xr);
Potential example for Foo[]
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.
添加另一个类Foos并从类Foo中删除xmlroot标记。
namespace Example
{
[XmlRoot("foos")]
class Foos
{
public Foos() {}
[XmlElement("foo")]
public List<Foo> FooList {get; set;}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.