user2336660
user2336660

Reputation:

how to extract data from an XML document

I have two classes called Movie and Movie Type and im trying to create objects of that classes based on the given example xml.

public class Movie
{
  public string title;
  public string rating; //can always convert.toin32 later
}

public class Genre
{
 int id;
 string genreType;
}

I would like to create objects of that class based on the following XML, what would be the best/fastest way?

<movie> 
<title> se7en </title> 
<genre> thriller</genre> 
<rating> 18 </rating> 
</movie> 
<movie> 
<title> zodiac </title> 
<genre> thriller</genre> 
<rating> 18 </rating>
</movie>

Upvotes: 1

Views: 91

Answers (2)

puko
puko

Reputation: 2970

or this

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

Upvotes: 2

Dgan
Dgan

Reputation: 10285

try this

Better will be LINQ to 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();

Upvotes: 3

Related Questions