动态嵌套XElements

时间:2013-03-13 16:02:54

标签: c# asp.net xml linq xelement

我希望创建一个XML,其中包含以下内容: -

<?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 个答案:

答案 0 :(得分: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