2013-03-13 101 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