I\'ve searched but couldn\'t find anything similar as this is probably very basic. I\'m basically trying to read a list of movies from an xml file and then to pass it back i
I think you are better off with using XmlSerializer
if the structure of your xml file is resembled in your classes by inheritance.
Write a function which Deserialize your xml to your classes.
public static MovieSummary Deserialize()
{
XmlSerializer serializer = new XmlSerializer(typeof(MovieSummary));
TextReader textReader;
textReader = new StreamReader(pathtoyourxmlfile);
MovieSummary summary = (MovieSummary)serializer.Deserialize(textReader);
textReader.Close();
return summary;
}
Hope that helps
If you are ONLY going to ever be loading a list of movies from an xml file, and that't it, you should check out the following link on MSDN: http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.getelementsbytagname%28v=vs.71%29.aspx
This would be a solution for that approach:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var xmlDoc = new XmlDocument();
xmlDoc.Load("c:\\movies.xml");
var movieModel = new MovieSummary();
var MovieXML = xmlDoc.GetElementsByTagName("movie");
movieModel.Movies = new List<Movie>();
foreach (XmlElement element in MovieXML)
{
movieModel.Movies.Add(new Movie(){movie = element.InnerText});
}
//for (i = 0; i < MovieXML.Count; i++)
//{
// movieModel.Movies[i].name = MovieXML[i]["name"].toString();
//}
}
}
}
If you are going to plan on loading anything more than just movies from the xml file or you think you'll ever need more flexibility in loading multiple nodes from multiple xml files, I'd advise using the xmlserialization ability of .NET via the xsd.exe tool. Do your xml files adhere to a common xsd schema. If they dont, dont worry, you can create a common schema for your xml files using xsd.exe (its part of visual studio). Once you have generated the xsd file from your sample xml file, you can use that xsd file to generate classes using that same xsd.exe tool.
Once that is done, you can add the generated class or classes to your model as members, wrap them as you see fit, and bulk load the data from the xml file into the member classes with a few lines of code. And that will work for any xml file so long as it adheres to said xsd file. You an also load and unload the data to and from xml file to and from classes using serializer classes.
There are many ways to do what you are talking about, and I've tried many ways. However, this by far the best way to do things because it allows you to load as many different xml files as you want without having to rewrite the methods that load the xml (Again, as long as what you're loading adheres to the xsd file).
http://msdn.microsoft.com/en-us/library/x6c1kb0s%28v=vs.71%29.aspx