【问题标题】:How to add more Attribute in XElement?如何在 XElement 中添加更多属性?
【发布时间】:2012-08-30 20:48:02
【问题描述】:

我有一个如下的数据结构

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 添加到我的程序中。

请帮忙

【问题讨论】:

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


    【解决方案1】:

    找到了

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

    【讨论】:

      【解决方案2】:

      你可以这样做:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多