我想创建一个XML,这将包括一些如下: -动态嵌套XElements
<?xml version="1.0" encoding="utf-8"?>
<Groups>
<Group>
<Id>1</Id>
<GroupName>Group1</CategoryId>
<Products>
<Product>
<ProductId>1</ProductId>
<ProductName>Apples</ProductName>
</Product>
<Product>
<ProductId>2</ProductId>
<ProductName>Oranges</ProductName>
</Product>
<Product>
<ProductId>3</ProductId>
<ProductName>Lemons</ProductName>
</Product>
</Products>
<DateCreated></DateCreated>
<DateModified></DateModified>
</Group>
<Group>
<Id>2</Id>
<GroupName>Group2</CategoryId>
<Products>
<Product>
<ProductId>3</ProductId>
<ProductName>Grapes</ProductName>
</Product>
<Product>
<ProductId>4</ProductId>
<ProductName>PineApple</ProductName>
</Product>
</Products>
<DateCreated></DateCreated>
<DateModified></DateModified>
</Group>
</Groups>
你可以从我的例子中看到的,Product
量可以从1组改变到另一个。
我该如何创建一个动态XML并且能够在以后读取相同的XML。
目前我的代码来创建XML如下:
internal XElement ConstructGroupXML(int numberOfItems)
{
XElement xmlList = new XElement("Groups",
from a in dataModel.CreateGroupList(numberOfItems)
select new XElement("Group",
new XElement("Id", a.Id),
new XElement("GroupName", a.GroupName),
new XElement("Products",
new XElement("ProductId", a.Products[i].Id),
new XElement("ProductName", a.Products[i].ProductName),
new XElement("CategoryId", a.Products[i].Category.Id),
new XElement("CategoryName", a.Products[i].Category.CategoryName),
new XElement("SubCategoryId", a.Products[i].SubCategory.Id),
new XElement("SubCategoryName", a.Products[i].SubCategory.SubCategoryName),
new XElement("DateCreated", a.DateCreated),
new XElement("DateModified", a.DateModified)
)
);
return xmlList;
}
的CreateGroupList
方法返回与组和嵌入这些组的产品名单的对象,所以每个组我想循环在产品列表中并生成XML。
你可以添加'CreateGroupList(numberOfItems)'的代码?你在'new XElement(“DateModified”,a.DateModified)));'它应该是'new XElement(“DateModified”,a.DateModified)'));' – 2013-03-13 16:14:18
是的,你错过了一个右括号正确的括号。 AddGroup没什么特别之处,只是循环使用某些产品并将它们添加到列表中,并将它们附加到组中。它在一个Group对象 – Johann 2013-03-13 16:20:22