2013-03-13 148 views
-1

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

+1

你可以添加'CreateGroupList(numberOfItems)'的代碼?你在'new XElement(「DateModified」,a.DateModified)));'它應該是'new XElement(「DateModified」,a.DateModified)'));' – 2013-03-13 16:14:18

+0

是的,你錯過了一個右括號正確的括號。 AddGroup沒什麼特別之處,只是循環使用某些產品並將它們添加到列表中,並將它們附加到組中。它在一個Group對象 – Johann 2013-03-13 16:20:22

回答

1

好,我設法找到解決辦法:

from o in a.Products 
select new XElement("Products", 
    new XAttribute("ProductId", o.Id), 
    new XElement("ProductName", o.ProductName), 
    new XElement("CategoryId", o.Category.Id), 
    new XElement("CategoryName", o.Category.CategoryName), 
    new XElement("SubCategoryId", o.SubCategory.Id), 
    new XElement("SubCategoryName", o.SubCategory.SubCategoryName), 

現在我只需要找出如何閱讀本XML

+0

內的列表我總是想知道爲什麼人們爲Product類使用'''''Group'類和'o'變量。看起來像變量名稱'g'和'p'已經用於蘋果和洋蔥.. – 2013-03-14 07:31:05

+0

謝謝@約翰,這就是我需要的! – mack 2017-10-17 17:50:25