MVC4应用程序中的XML文档错误

时间:2013-07-06 02:42:42

标签: c# xml

获得以下错误。似乎从其他线程可能有很多可能的原因。我保持我的代码尽可能简单。

    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>

1 个答案:

答案 0 :(得分:0)

您的根对象是MovieSummary类型。因此序列化程序需要一个根<MovieSummary>元素。使用XmlRoot和XmlElement属性重命名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; }
}