2015-02-11 83 views
1

我有两个名为Movie和Movie Type的类,我试图根据给出的示例xml创建该类的对象。如何从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

[转换XML使用反射对象](HTTP可能重复:// stackoverflow.com/questions/3268912/convert-xml-to-object-using-reflection) – Bio42 2015-02-11 09:59:06

+0

可能使用Linq查询记录的Xml文件的副本(http://stackoverflow.com/questions/26422431/query-xml-file-for-records-using-linq) – 2015-02-11 10:20:26

回答

4

尝试这种

更好将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(); 
+0

如果您分为两个类,该怎么办?例如 class电影{0} {0} 字符串评分; } class类型 { string类型; } } 考虑到您可以在选择的新Movie()中创建一个新对象,该怎么办? – 2015-02-11 12:20:15

3

或该

var xml = @"<movie/>"; 
var serializer = new XmlSerializer(typeof(Movie)); 
using (var reader = new StringReader(xml)) 
{ 
    var movie = (Movie)serializer.Deserialize(reader); 
}