Search code examples
c#xmlxelement

how to use create a xml document with Xelement


I am trying to create a xml document using Xelement. I have a List of 2 objects, Data and Products. each has a list of objects. the xml document needs to be setup like this

<Property>
  <Points>
   <Sqft>1432</Sqft>
   <Price>45666</Price>
   <Product>Product Name</Product>
 </Points>
</Property>

Here is the code that I am using, of course it doesn't work but it is what I would theoretically need it to do.

var xEleProperty = new XElement("Property",
                        from item in Property.Data && item1 in Property.Products
                        select new XElement("points",
                                     new XElement("Sqft", item.sqft),
                                     new XElement("Price", item.price),
                                     new XElement("Product", item1.product)
                                   ));

Solution

  • The below works, you need the Id properties to join the two collections, otherwise you will get duplicate records:

    class Program
    {
        static void Main(string[] args)
        {
            var data = new List<Data>();
            var products = new List<Product>();
    
            data.Add(new Data { ProductId = 1, Price = 321.0, Sqft = 789 });
            products.Add(new Product { Id = 1, Name = "SomeProduct 1" });
    
            data.Add(new Data { ProductId = 2, Price = 123.0, Sqft = 456 });
            products.Add(new Product { Id = 2, Name = "SomeProduct 2" });
    
            var xEleProperty = new XElement("Property",
                         from d in data
                         join product in products on d.ProductId equals product.Id
                         select new XElement("Points",
                                      new XElement("Sqft", d.Sqft),
                                      new XElement("Price", d.Price),
                                      new XElement("Product", product.Name)
                                    ));
            Console.WriteLine(xEleProperty);
            Console.ReadLine();
        }
    }
    
    public class Data
    {
        public int ProductId { get; set; }
        public double Price { get; set; }
        public int Sqft { get; set; }
    }
    
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    

    the output is:

    <Property>
      <Points>
        <Sqft>789</Sqft>
        <Price>321</Price>
        <Product>SomeProduct 1</Product>
      </Points>
      <Points>
        <Sqft>456</Sqft>
        <Price>123</Price>
        <Product>SomeProduct 2</Product>
      </Points>
    </Property>