Friday, February 12, 2010

Reading and Writing XML with Linq

In this sample, I am using Linq to construct my objects into XML, then being able to read the XML with Linq and construct it back into my class objects.

Writing (Linq to XML):

var xmlFile = 
new XElement("Movies",
from m in movies
select new XElement("Movie",
new XElement("Title", m.Title),
new XElement("Director", m.Director),
new XElement("ReleaseDate", m.ReleaseDate),
new XElement("Casts",
from c in m.Casts
select new XElement("Cast",
new XElement("Name", c.Name),
new XElement("Dob", c.Dob),
new XElement("Roles",
from r in c.Roles
select new XElement("Role",
new XElement("MovieName", r.Movie),
new XElement("RoleName", r.RoleName)))))));

Reading (XML to Linq):

var movies = 
from m in xmlFile.Descendants("Movie")
select new Movie
Title = (string)m.Element("Title"),
Director = (string)m.Element("Director"),
ReleaseDate = (DateTime)m.Element("ReleaseDate"),
Casts = (from c in m.Elements("Casts").Descendants("Cast")
select new Cast
Name = (string)c.Element("Name"),
Dob = (DateTime)c.Element("Dob"),
Roles = (from r in c.Elements("Roles").Descendants("Role")
select new Role
Movie = (string)r.Element("MovieName"),
RoleName = (string)r.Element("RoleName")

Reading and Writing Xml Files

Please let me know if this helps you.