READ XML IN ASP.NET CORE

Asked

Viewed 64 times

-3

Great, I’m working on a project that consists of reading XML files, but I have a problem. The XML file has several subchilds.

<?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 an XML I have. Now I can read the id, name, price and Quantity but when it comes to reading the Description I can’t read it anymore.

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

I made this code in c#. What else do I need to add here? I wonder if I have to create another Controller to read Description. I appreciate the help right now!! (I’ve been trying to do this for over a week now!!)

  • reflects the xml structure in classes and you will understand how to manipulate

1 answer

0


I don’t know if this is what you want but I found it very simple, just you navigate the element "Description".

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),
               Comment = p.Element("description").Element("comment").Value
            }).ToList();

I put an example on Dotnetfiddle and published here too Github

Browser other questions tagged

You are not signed in. Login or sign up in order to post.