我有两个名为Movie和Movie Type的类,我试图根据给定的示例xml创建该类的对象。
public class Movie
{
public string title;
public string rating; //can always convert.toin32 later
}
public class Genre
{
int id;
string genreType;
}
我想基于以下XML创建该类的对象,最佳/最快的方式是什么?
<movie>
<title> se7en </title>
<genre> thriller</genre>
<rating> 18 </rating>
</movie>
<movie>
<title> zodiac </title>
<genre> thriller</genre>
<rating> 18 </rating>
</movie>
答案 0 :(得分:3)
试试这个
最好是LINQ
到XML
XDocument document = XDocument.Load("MyDoc.xml");
List<Movie> statusList = (from movies in document.Descendants("Movie")
select new Movie()
{
title = movies.Element("title").Value,
rating = movies.Element("rating").Value,
genre = movies.Element("genre").Value
}).ToList();
答案 1 :(得分:2)
或者
var xml = @"<movie/>";
var serializer = new XmlSerializer(typeof(Movie));
using (var reader = new StringReader(xml))
{
var movie = (Movie)serializer.Deserialize(reader);
}