2012-09-06 45 views
5

我有一個數據結構,如如何在XElement中添加更多屬性?

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; } 
} 

現在讓我們填充到它的一些價值

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; 

的願望輸出

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

我的計劃至今

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

這使我的輸出作爲

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

我怎樣才能屬性數量和PurchaseType其餘添加到我的計劃。

請幫

回答

8

我發現它

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

你可以簡單地這樣做:

yourXElement.Add(new XAttribute("Quantity", "2")); 
yourXElement.Add(new XAttribute("PurchaseType", "3"));