0

收到以下错误。似乎其他线程可能有很多可能的原因。我使我的代码尽可能简单。

    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>
4

1 回答 1

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; }
}
于 2013-07-06T03:10:22.257 回答