1

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

EDIT:

I am going to have to give the user of adding/removing stock to the cart as they wish. I imagine the code for doing that then would be something like, after displaying the details of all 10 objects (recordnumber, name, stock, price)

String input = Console.ReadLine();
foreach (var prod in result) {
  if (input == prod.recordnumber) {   // Assuming that user selects via indexnumber
   cart.AddProduct(//no idea what to put from here on
  }
}  

Am I on the right track?

Second EDIT:

String productNumber = Console.ReadLine();
int productInt = Convert.ToInt32(productNumber);

var match = from p in result
where p.RecordNumber == productInt
   select p;

 if (match != null)
 {
   ShoppingCart.AddProduct(??);  //what variable do I put in the parentheses?
                                 // Need to also reduce stock
 }
   else
 {
    // Inform user that no product exists
 }

As I said below, I'm totally at a loss as to what to put in the parentheses. i have tried match and p but obviously they're not right. Once I know how to refer to the object I should also be able to reduce the stock number for the object and put another instance into the list.

Thanks again for helping me out

5
  • Have a look at something called "Serialization". msdn.microsoft.com/en-us/library/ms973893.aspx Commented Aug 11, 2014 at 8:45
  • 1
    Assumihng no exceptions and valid/well-formed xml in the file. Yes, you are loading the XML, the "var result" will hold an IQueryable which you can use to access the items in the collection. Commented Aug 11, 2014 at 8:47
  • cart.AddProduct(match) Commented Aug 12, 2014 at 9:16
  • but the AddProduct method requires a Product? not var? I get the following error: The best overloaded method has some invalid arguments. And changing the method to accept var doesnt work Commented Aug 12, 2014 at 9:26
  • I was missing a FirstOrDefault(). The "match" is actually a new collection with all products matching the specified record number, but there should only be one (since it's unique), so you just need to grab the first one. I have updated my answer. You probably need to dig deeper into Linq - or stick with your original foreach, in which case you just add "prod" to your cart. Commented Aug 12, 2014 at 9:28

2 Answers 2

1

Your program is loading 10 product items in the the result variable, and the it exits. To put them in the cart, you need to construct a Cart object, and add each product item to the cart:

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)
             };

    var cart = new Cart();

    // Logic to add/remove/list cart here
}

To allow the user to add/remove items from the cart, you would need to have an identifier whether the add/remove/list, and the which item. This will have to be in a loop. You would probably also have an exit condition. So something in the lines of this:

var cmd = string.Empty;
do
{
    // Loop to allow the user to keep entering commands

    cmd = Console.ReadLine();        
    // if cmd == exit condition -> break;    
    // if cmd == list products condition -> write each prod to console
    // if cmd == add product condition -> Ask user to enter product number and add to cart
    // if cmd == remove product condition -> Ask user to enter product number and remove from cart
} while(true);

When the user enters the product number, you can find the correct product using linq:

var match = (from p in result
            where p.RecordNumber == productNumber
            select p).FirstOrDefault();

if (match != null)
{
    // Add/remove
}
else
{
    // Inform user that no product exists
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hey, thanks a lot!! This is super helpful. Well for the assignment I have to give the user the option of adding whatever objects they want to the cart, or deleting whatever objects they want from the cart, then displaying the cart and 'purchasing' a cart(updating of XML file and emptying of cart after displaying price). Woops didnt realise how this works, ill edit the original
Thanks. I don't think I really have any issues with the building of the control flow. I've got a switch at the moment. I'll edit my post again...I have a problem with adding/removing products to the cart...I'm used to objects being given references or names so I am getting quite lost with how to refer to them.
0

You can use XmlSerializer:

var xmlSerializer = new XmlSerializer(typeof(List<Product>));

List<Product> productList;
using (var fileStreamReader = File.OpenRead("inventory.xml"));
{
    productList = (List<Product>) xmlSerializer.Deserialize(fileStreamReader);
}

Using LINQ 2 XML is ok, but if all you want to do is deserialize the XML into an object representation, serialization is easier.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.