我使用Linq to XML创建一个xml,值在Product对象中。 请参阅下面的c#代码段,生成xml:
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节点。 即,代码片段中的上述p.SKU是字符串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; }
}
答案 0 :(得分: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>
所以这正是你想要实现的目标,不是吗?