Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Read XML File in ASP.NET CORE MVC

$
0
0

Hi,

I am working on a project where i have to read an xml file.

But I have a problem. 

<?xml version="1.0" encoding="utf-8" ?><products><product><id>100</id><name>Ball</name><price>15</price><quantity>2</quantity><description><comment>aaa</comment></description></product></products>

This is an example of the file that I have to import and read.

I can read id, name, price and quantity. I cant read description.

Bellow i will show my code in c#.

private List<Product> ProcessImport(string path)
    {
        XDocument xDocument = XDocument.Load(path);
        List<Product> products = xDocument.Descendants("product").Select
            (p => new Product()
            {
               Id = Convert.ToInt32(p.Element("id").Value),
               Name=p.Element("name").Value,
               Quantity = Convert.ToInt32(p.Element("quantity").Value),
               Price = Convert.ToDecimal(p.Element("price").Value),




            }).ToList();
        foreach(var product in products)
        {
            var productInfo = db.Products.SingleOrDefault(p => p.Id.Equals(product.Id));
            if(productInfo != null)
            {
                productInfo.Id = product.Id;
                productInfo.Name = product.Name;
                productInfo.Quantity = product.Quantity;
                productInfo.Price = product.Price;


            }
            else
            {
                db.Products.Add(product);
            }

            db.SaveChanges();
        }
        return products;
    }

Do I have to do anything different?

Can you help me!?!?!?

Thanks!!


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>