1

我目前在尝试将我的 XML 元素导入书籍类型列表时遇到问题。我在这段代码中收到“未设置对象实例的对象引用”错误:

mybook.Title = p.Element("title").Value;

我是否不正确地引用了 XML 元素,还是其他一些简单的问题?我已经通过无尽的解决方案和主题连续搜索了几个小时,但无法克服最后一个障碍。

为简单起见,以下是一个文件中的代码:

class Program
{
    static void Main(string[] args)
    {
        string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        FileInfo fi = new FileInfo(Path.Combine(appPath, "Books.xml"));

        Console.WriteLine(GetBooks());
    }

    public class Books
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
        public decimal Price { get; set; }
        public DateTime PublishDate { get; set; }
        public string Description { get; set; }
    }

    public static List<Books> GetBooks()
    {
        XDocument doc = LinqToXml.XmlHelper.GetPlantDocument();
        var xmlBooks = doc.Descendants("catalog");
        List<Books> someBooks = new List<Books>();

        foreach (var p in xmlBooks)
        {
            Books mybook = new Books();
            mybook.Title = p.Element("title").Value;
            someBooks.Add(mybook);
        }
        return someBooks;
    }
}

这是 XML 文件的内容:

http://pastebin.com/ZVmWqRT1

请注意,这确实是一个家庭作业项目。我不一定要寻找直接答案,因为我是一两个巨大的提示。

4

1 回答 1

1
XElement doc=XElement.Load("c:\\hello.xml");

List<Books> lstBooks=doc.Elements("book").Select(x=>
new Books
{
        ID=x.Attribute("id").Value,
        Name=x.Element("author").Value,
        Title =x.Element("title").Value,
        Price =decimal.Parse(x.Element("price").Value),
        PublishDate =Convert.ToDateTime(x.Element("publish_date").Value),
        Description=x.Element("description").Value
}
).ToList(); 

//lstBooks now contain all the books
foreach(Books b in lstBooks)
{
         b.ID;
         b.Name;...........
}
于 2012-10-06T03:19:40.133 回答