Creating objects in C# out of XML using LINQ



Hey so I'll start out by saying this is for an assignment...I have to create a console-based shopping cart that loads and saves to an XML file.


I can't quite work out how to load the XML file into objects/what the best way of doing this is....



class Product
{
public int RecordNumber { get; set; }
public String Name { get; set; }
public int Stock { get; set; }
public int Price { get; set; }
}
class Cart
{

public List<Product> items
{
get { return items; }
set { items = value; }
}

public Cart() {} //Right way to do constructor?

public void AddProduct(Product prod)
{
items.Add(prod);
}

public void RemoveProduct(Product prod)
{
items.Remove(prod);
}
}

static void Main(string[] args)
{
XDocument XDoc = XDocument.Load("inventory.xml"); // Loading XML file
var result = from q in XDoc.Descendants("product")
select new Product
{
RecordNumber = Convert.ToInt32(q.Element("recordNumber").Value),
Name = q.Element("name").Value,
Stock = Convert.ToInt32(q.Element("stock").Value),
Price = Convert.ToInt32(q.Element("price").Value)
};


XML file is set up as follows (theres ten entries of products):



<product>
<recordNumber>1</recordNumber>
<name>Floo Powder</name>
<stock>100</stock>
<price>5</price>
</product>


I have two questions here...Is my main method loading the XML file and creating 10 objects? If so, how do I access these objects?


Secondly, I was going to be adding Products to the cart, and then reducing the 'stock' figure, but when I think about it that seems wrong. Should I be creating an object for every single one of the stock available, and then adding them to the cart? Any advice on how I might be able to do that instead then?


Thanks so much!!


No comments:

Post a Comment