How to add more Attribute in XElement?

15,973

Solution 1

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)
                                    ))

Solution 2

You can simply do this:

yourXElement.Add(new XAttribute("Quantity", "2"));
yourXElement.Add(new XAttribute("PurchaseType", "3"));
Share:
15,973
Niladri Biswas
Author by

Niladri Biswas

Updated on July 15, 2022

Comments

  • Niladri Biswas
    Niladri Biswas almost 2 years

    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