如果你有这样的格式的数据:
<Person>
<Id>1</Id>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
</Person>
那么这个C#代码desrialise成Person实例
//assuming you have a string called "data" that contains the above XML.
XDocument xd=XDocument.Parse(data); //needs System.Xml.Linq for XDocument type.
using(var reader = xd.CreateReader())
{
using(XmlSerializer ser = new XmlSerializer(typeof(Person))
{
Person p = ser.Deserialize(reader) as Person;
//p will be null if it didn't work, so make sure to check it!
}
}
注意,解串器是大小写敏感的,所以你需要以确保元素案例与你的类中的属性框架相匹配(你可以通过使用Serializer属性装饰你的属性来告诉序列化者如何映射他们的属性here)
纯原生序列化器非常适合这样的简单对象,但可能会让你在char,bool等数据类型上出现问题,因此请检查该属性上的链接。
如果你想从你在问题中提供的格式来完成它,你需要编写一个自定义的串行器,在你的情况下,我的建议是从你的文件中读取数据并使用XDocument这有助于。
您是否考虑过使用更标准的数据交换格式,如JSON,SEN或XML? – 2013-03-09 14:59:03