我想創建一個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