创建用于获取、更新、删除电影的应用程序
我试图从XML文件中获取电影列表,但每次我在WebService测试仪上尝试获取电影列表时,我都会遇到这个错误
'对象引用未设置为对象的实例。'System.Xml.Linq.XElement.Attribute(…(返回null
我的代码
public class Movie
{
private static string _xmlDataPath = HttpContext.Current.Server.MapPath("~/App_Data/Movies.xml");
public int Id { get; set; }
public string Title { get; set; }
public string Director { get; set; }
public string Synopsis { get; set; }
public Movie(int id, string title, string director, string sypnosis)
{
this.Id = id;
this.Title = title;
this.Director = director;
this.Synopsis = sypnosis;
}
public XElement toXML(XNamespace ns)
{
return new XElement(ns + "Movie",
new XElement(ns + "Id", this.Id),
new XElement(ns + "Title", this.Title),
new XElement(ns + "Director", this.Director),
new XElement(ns + "Sypnosis", this.Synopsis)
);
}
public static List<Movie> GetAllMovies()
{
List<Movie> movieList = new List<Movie>();
//Load XML file using LINQ
XDocument doc = XDocument.Load(_xmlDataPath);
var xmlMoviesList = doc.Root.Elements();
XNamespace ns = doc.Root.GetDefaultNamespace();
//Get each movie element from XML
foreach (var xmlMovies in xmlMoviesList)
{
Movie movie = new Movie(
int.Parse(xmlMovies.Attribute("Id").Value),
xmlMovies.Element(ns + "Title").Value,
xmlMovies.Element(ns + "Director").Value,
xmlMovies.Element(ns + "Sypnosis").Value
);
//Add to the list
movieList.Add(movie);
}
//Return the list
return movieList;
}
如果您能包含示例XML,那就太好了,否则人们不得不猜测。
使用Id
作为属性,您的代码可以很好地解析这个XML文件。
<Root>
<Movie Id="1">
<Title>Alien</Title>
<Director>Ridley Scott</Director>
<Sypnosis>In space no one can hear you scream.</Sypnosis>
</Movie>
</Root>
但是,您编写的toXML
函数生成了这个XML,它将Id
作为节点
<Root>
<Movie>
<Id>1</Id>
<Title>Alien</Title>
<Director>Ridley Scott</Director>
<Sypnosis>In space no one can hear you scream.</Sypnosis>
</Movie>
</Root>
决定Id
是一个属性还是一个节点,并相应地调整代码。将new XElement(ns + "Id", this.Id),
更改为new XAttribute(ns + "Id", this.Id)
,或将xmlMovies.Attribute("Id").Value
更改为xmlMovies.Element(ns + "Id").Value
附带说明一下,请查看int.TryParse
的文档,并尝试使用它来代替int.Parse
。最好确保您首先在要解析的数据中有一个整数