0

我正在使用 Linq to XML 创建一个 xml,这些值位于 Product 对象中。请参阅下面生成 xml 的 c# 代码片段:

new XElement(xn + "Products",
                    from p in products
                    select
                        new XElement(xn + "Product",
                            new XElement(xn + "ProductId", p.Id),
                            new XElement(xn + "Name", p.Name),
                            new XElement(xn + "Description", new XCData(p.LongDescription.StripHtml())),
                            new XElement(xn + "CategoryExternalId",
                                from c in categories
                                where c.Name == p.PrimaryCategory
                                select c.CategoryId),
                            new XElement(xn + "UPCs",
                                from s in p.SKU
                                select
                                    new XElement(xn + "UPC", s.UPC))))
                        ));

挑战在于 UPC。如果产品 SKU 数组中没有 UPC 条目,我不想创建 UPCs xml 节点。上面代码片段中的iepSKU,是一个字符串UPC字段的数组。因此,如果不存在单个 UPC 字段,即如果p.SKU.Count ==0,那么我根本不希望创建 UPC xml 节点元素。

查看类模型片段:

public class Product
{
   public string Name { get; set; }
   public string Description { get; set; }
   public List<SKU> SKU { get; set; }
}

public class SKU
{
    public string UPC { get; set; }
    public string Name { get; set; }
    public string Overlap { get; set; }
    public string Productline { get; set; }
}
4

1 回答 1

2

将其放在您的查询中:

(p.SKU.Count > 0 ? 
    new XElement("UPCs",
        from s in p.SKU
        select new XElement( "UPC", s.UPC)) :
    null)

我创建了您的查询的简化版本:

var xml = new XElement("Products",
                    from p in products
                    select
                        new XElement("Product",
                            new XElement("ProductId", p.Id),
                            new XElement("Name", p.Name),
                            (p.SKU.Count > 0 ? new XElement("UPCs",
                                                    from s in p.SKU
                                                    select new XElement("UPC", s.UPC))
                                                : null)));

对于这样的输入:

var products = new List<Product> {
    new Product {
        Id = 1,
        Name = "TestName",
        SKU = new List<SKU> {
            new SKU { Name = "test", UPC = "UPC1" },
            new SKU { Name = "test2", UPC = "UPC2" }
        }
    },
    new Product {
        Id = 1,
        Name = "TestName",
        SKU = new List<SKU> { }
    }
};

输出是:

<Products>
  <Product>
    <ProductId>1</ProductId>
    <Name>TestName</Name>
    <UPCs>
      <UPC>UPC1</UPC>
      <UPC>UPC2</UPC>
    </UPCs>
  </Product>
  <Product>
    <ProductId>1</ProductId>
    <Name>TestName</Name>
  </Product>
</Products>

所以这正是你想要达到的目标,不是吗?

于 2013-03-12T19:31:49.320 回答