Service 元素将始终为空,因为您实际上从未向其中添加任何内容,您只是创建它。您将产品添加到 Catalog 元素,而不是将它们添加到 Service 元素。
此外,将这些“根”称为不正确的术语,因为有效的 XML 文档只能有一个根(因此在这种情况下,唯一的根元素是 Catalog)。
代码如下:
public class Product
{
public string ProductName { get; set; }
public string VariantName { get; set; }
public string SKU { get; set; }
}
private static void CreateDoc(List<Product> list)
{
XElement serviceElement = new XElement("Service");
XElement rootElement = new XElement("Catalog", serviceElement);//Create a root Element
// Obviously include the foreach loop
foreach (Product product in list)
{
// Obviously replace these hardcoded string with your actual object values
XElement productElement = new XElement("Product", new XAttribute("name", product.ProductName));//Read the Product
XElement variantElement = new XElement("Variant", new XAttribute("name", product.VariantName));//Read variant
XElement skuElement = new XElement("SKU", new XAttribute("name", product.SKU));//Read SKU
productElement.Add(variantElement, skuElement);//Add varaint and skuvariant to product
// Add product to the Service element, NOT to the root. The root is Catalog.
serviceElement.Add(productElement);
}
rootElement.Save("XmlFile.xml");
}
主要变化是
// Store the Service element is a variable so we can add stuff to it
XElement serviceElement = new XElement("Service");
// ...
// Add to the Service element instead of to Catalog
serviceElement.Add(productElement);
我这样称呼它:
List<Product> list = new List<Product>
{
new Product { ProductName = "SomeName", SKU = "SomeSKU", VariantName = "VariantA" },
new Product { ProductName = "AnotherProduct", SKU = "AnotherSKU", VariantName = "VariantB" },
new Product { ProductName = "ProductC", SKU = "SKUc", VariantName = "VariantC" }
};
CreateDoc(list);
这是生成的 XML:
<?xml version="1.0" encoding="utf-8"?>
<!-- Catalog is the root element for this document -->
<Catalog>
<!-- Service is NOT a root element, even though it's the only child of Catalog -->
<Service>
<!-- Each Service element can have an arbitrary number of Product elements -->
<Product name="SomeName">
<Variant name="VariantA" />
<SKU name="SomeSKU" />
</Product>
<Product name="AnotherProduct">
<Variant name="VariantB" />
<SKU name="AnotherSKU" />
</Product>
<Product name="ProductC">
<Variant name="VariantC" />
<SKU name="SKUc" />
</Product>
</Service>
</Catalog>
另一个澄清 - 在这种情况下 Service 不是 根元素(即使在这种情况下它是 Catalog 的唯一子元素)。