0

Getting the following error. Seems like there could be many possible reasons for this from other threads. I've kept my code as simple as possible.

    There is an error in XML document (2, 2).

    public class MovieSummary
    {
         public List<Movie> Movies { get; set; }
    }

    public class Movie
    {
         public int id { get; set; }
         public string name { get; set; }
    }


    public static MovieSummary Deserialize()
    {
        using (TextReader reader = new StreamReader("c:\\movies.xml"))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(MovieSummary));
            return (MovieSummary)serializer.Deserialize(reader);
        }
    }

    public ActionResult GetListOfMovies()
    {
        MovieSummary summary = Deserialize();
        return View(summary);
    }

    <?xml version="1.0" ?> 
    <movies xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
     <movie>
      <id>1</id>
      <name>The Dark Knight</name>
     </movie>
    </movies>
Michael Bray
  • 14,998
  • 7
  • 42
  • 68
totalnoob
  • 2,521
  • 8
  • 35
  • 69

1 Answers1

0

Your root object is of type MovieSummary. So the serializer is expecting a root <MovieSummary> element. Use the XmlRoot and XmlElement attributes to rename your elements in the xml:

[XmlRoot("movies")]
public class MovieSummary
{
    [XmlElement("movie")]
    public List<Movie> Movies { get; set; }
}


public class Movie
{
    public int id { get; set; }
    public string name { get; set; }
}
fcuesta
  • 4,429
  • 1
  • 18
  • 13
  • your answer works. why wouldn't it work though, if instead I did indeed add as the root in my xml document? I got the same error when I did – totalnoob Jul 06 '13 at 05:52