Reputation: 47
I am currently experiencing an issue trying to import my XML elements into a list of type Books. I am receiving an 'Object reference not set to an instance of an object' error on this piece of code:
mybook.Title = p.Element("title").Value;
Am I referencing the XML element improperly or is it some other simple matter? I have googled for hours on end through endless solutions and topics and can not get over this last hurdle.
For simplicity, here is the code in one file:
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;
}
}
This is the contents of the XML file:
Please note that this is indeed a homework project. I am not looking for a direct answer necessarily as I am a giant hint or two.
Upvotes: 1
Views: 1717
Reputation: 32807
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;...........
}
Upvotes: 1