动态嵌套的xelement

本文关键字:xelement 嵌套 动态 | 更新日期: 2023-09-27 18:03:39

我希望创建一个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的数量可以从一个组变化到另一个组。

我如何创建一个动态的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方法返回一个对象,其中包含组和嵌入在这些组中的产品列表,因此对于每个组,我希望在Product List中循环并生成XML。

动态嵌套的xelement

我找到了解决方案:

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