如何在XElement中添加更多属性?

时间:2012-09-06 04:56:07

标签: c#-4.0 linq-to-xml xattribute

我有

下的数据结构
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>

如何将其余属性 Quantity和PurchaseType 添加到我的程序中。

请帮忙

2 个答案:

答案 0 :(得分:8)

我找到了

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

答案 1 :(得分:5)

你可以这样做:

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