如何从XML文档中提取数据

时间:2015-02-11 09:55:23

标签: c# xml linq

我有两个名为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>

2 个答案:

答案 0 :(得分:3)

试试这个

最好是LINQXML

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