How to add more Attribute in XElement?

Niladri Biswas picture Niladri Biswas · Sep 6, 2012 · Viewed 16k times · Source

I have a data structure as under

class BasketCondition
{
        public List<Sku> SkuList { get; set; }
        public string InnerBoolean { get; set; }
}

class Sku
{
        public string SkuName { get; set; }
        public int Quantity { get; set; }
        public int PurchaseType { get; set; }
}

Now let us populate some value to it

var skuList = new List<Sku>();
skuList.Add(new Sku { SkuName = "TSBECE-AA", Quantity = 2, PurchaseType = 3 });
skuList.Add(new Sku { SkuName = "TSEECE-AA", Quantity = 5, PurchaseType = 3 });

BasketCondition bc = new BasketCondition();
bc.InnerBoolean = "OR";
bc.SkuList = skuList;

The desire output is

<BasketCondition>
   <InnerBoolean Type="OR">
      <SKUs Sku="TSBECE-AA" Quantity="2" PurchaseType="3"/>
      <SKUs Sku="TSEECE-AA" Quantity="5" PurchaseType="3"/>
   </InnerBoolean>
</BasketCondition>

My program so far is

XDocument doc =
       new XDocument(
       new XElement("BasketCondition",

       new XElement("InnerBoolean", new XAttribute("Type", bc.InnerBoolean),
       bc.SkuList.Select(x => new XElement("SKUs", new XAttribute("Sku", x.SkuName)))
       )));

Which gives me the output as

<BasketCondition>
  <InnerBoolean Type="OR">
    <SKUs Sku="TSBECE-AA" />
    <SKUs Sku="TSEECE-AA" />
  </InnerBoolean>
</BasketCondition>

How can I add the rest of the attributes Quantity and PurchaseType to my program.

Please help

Answer

Niladri Biswas picture Niladri Biswas · Sep 6, 2012

I found it

bc.SkuList.Select(x => new XElement("SKUs", new XAttribute("Sku", x.SkuName),
                                            new XAttribute("Quantity", x.Quantity),
                                            new XAttribute("PurchaseType", x.PurchaseType)
                                    ))