Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add more Attribute in XElement?

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

like image 919
Niladri Biswas Avatar asked Sep 06 '12 04:09

Niladri Biswas


2 Answers

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)
                                    ))
like image 168
Niladri Biswas Avatar answered Sep 27 '22 23:09

Niladri Biswas


You can simply do this:

yourXElement.Add(new XAttribute("Quantity", "2"));
yourXElement.Add(new XAttribute("PurchaseType", "3"));
like image 42
kurt Avatar answered Sep 27 '22 23:09

kurt