stack overflow xml

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Linq;
	
public class Product
{
	public int Id { get; set; }
    public string Name { get; set; }
    public int Quantity { get; set; }
    public double Price { get; set; }
    public string Description { get; set; }
}

public class Program
{
	static List<Product> db = new List<Product>(); //apenas para siMular dados incluídos no DbSet de produtos
	
	public static void Main()
	{
		ProcessImport("");
	}
	
	private static List<Product> ProcessImport(string path)
	{
    //XDocument xDocument = XDocument.Load(path);
		XDocument xDocument= new XDocument(  
			new XElement("products",  
				new XElement("product",
					new XElement("id", "1"),
					new XElement("name", "Ball"),  
					new XElement("price", "15"),  
					new XElement("quantity", "2"),  
					new XElement("description",
						new XElement("comment", "aaa")),  
					new XElement("description",
						new XElement("comment", "bbb")),   
					new XElement("age", 
						new XElement("number", "12"))  
					)
			)  
		); 
    	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.ToDouble(p.Element("price").Value),
			   Description = string.Join(",", p.Descendants("description").Select(a => a.Element("comment").Value))
			}).ToList();

		foreach(var product in products)
		{
			//var productInfo = db.Products.SingleOrDefault(p => p.Id.Equals(product.Id));
			var productInfo = db.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;
				productInfo.Description= product.Description;
			}
			else 
			{
				//db.Products.Add(product);
				db.Add(product);
			}

			//db.SaveChanges();
			Console.WriteLine("Produto: " + db[db.Count - 1].Name + " Descrição:  " + db[db.Count - 1].Description + " -> incluído com sucesso");
		}

		return products;
	}
}
;