简体   繁体   English

使用LINQ用XML在C#中创建对象

[英]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. 嘿,所以我首先要说这是一项任务...我必须创建一个基于控制台的购物车,该购物车可以加载并保存到XML文件。

I can't quite work out how to load the XML file into objects/what the best way of doing this is.... 我还不太清楚如何将XML文件加载到对象中/什么是最好的方法。

 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): XML文件设置如下(产品的十个条目):

 <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? 我在这里有两个问题...我的主要方法是加载XML文件并创建10个对象吗? 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) 我认为执行此操作的代码将显示所有10个对象(记录编号,名称,股票,价格)的详细信息后类似

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. 我已经尝试过match和p,但显然他们是不对的。 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 再次感谢您的帮助

Your program is loading 10 product items in the the result variable, and the it exits. 您的程序正在结果变量中加载10个产品项,然后退出。 To put them in the cart, you need to construct a Cart object, and add each product item to the cart: 要将它们放入购物车,您需要构造一个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: 当用户输入产品编号时,您可以使用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
}

You can use XmlSerializer : 您可以使用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. 使用LINQ 2 XML是可以的,但是如果您要做的只是将XML反序列化为对象表示形式,则序列化会更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM