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