将嵌套集合转换为平面数据表

问题描述

我有一个嵌套的值集合(ID和名称),它们存储为XML。我想将此XML转换为单个数据表,同时保持父子关系。

<Apartment id="1A" name="Apartment 1A">
    <ApartmentComponent id="300" name="Living Room" />
    <ApartmentComponent id="301" name="Bathroom">
        <ApartmentComponent id="2698" name="Tub" />
        <ApartmentComponent id="8204" name="Sink" />
    </ApartmentComponent>
</Apartment>
<Apartment id="2A" name="Apartment 2A">
    <ApartmentComponent id="302" name="Dining Room">
        <ApartmentComponent id="2635" name="Table" />
        <ApartmentComponent id="2746" name="Cabinet" />
    </ApartmentComponent>
    <ApartmentComponent id="301" name="Bathroom">
        <ApartmentComponent id="8204" name="Sink">
            <ApartmentComponent id="56352" name="Drain Plug" />
        </ApartmentComponent>
    </ApartmentComponent>
</Apartment>

结果表看起来像这样...

+-------+--------------+-----------+--------------+
|   ID  |     Value    | Parent ID | Parent Value |
+-------+--------------+-----------+--------------+
|   1A  | Apartment 1A |           |              |
+-------+--------------+-----------+--------------+
|  300  |  Living Room |     1A    | Apartment 1A |
+-------+--------------+-----------+--------------+
|  301  |   Bathroom   |     1A    | Apartment 1A |
+-------+--------------+-----------+--------------+
|  2698 |      Tub     |    301    |   Bathroom   |
+-------+--------------+-----------+--------------+
|  8204 |     Sink     |    301    |   Bathroom   |
+-------+--------------+-----------+--------------+
|   2A  | Apartment 2A |           |              |
+-------+--------------+-----------+--------------+
|  302  |  Dining Room |     2A    | Apartment 2A |
+-------+--------------+-----------+--------------+
|  2635 |     Table    |    302    |  Dining Room |
+-------+--------------+-----------+--------------+
|  2746 |    Cabinet   |    302    |  Dining Room |
+-------+--------------+-----------+--------------+
|  301  |   Bathroom   |     2A    | Apartment 2A |
+-------+--------------+-----------+--------------+
|  8204 |     Sink     |    301    |   Bathroom   |
+-------+--------------+-----------+--------------+
| 56352 |  Drain Plug  |    8204   |     Sink     |
+-------+--------------+-----------+--------------+

我通常首先使用XDocument解析XML。这将给我一个我可以使用LINQ查询的集合。但是我不确定如何将结果集合解析为平面表结构。我需要使用递归函数吗?

解决方法

像上面提到的反射问题一样,XContainer.Descendants()无需递归即可执行此操作-或更确切地说,它将为您处理递归,一直到排水塞,甚至更多。

假设该代码段周围有一个<root>元素,因此XDocument will parse it normally

foreach (var element in xdoc.Root.Descendants())
{
    (string,string,string) values = (
        element.Attribute("id").Value,element.Attribute("name").Value,element.Parent?.Attribute("id")?.Value,element.Parent?.Attribute("name")?.Value
    );
    Console.WriteLine(values);
}
,

这种方法也可以作为获得所需解决方案的选择。

阶段1:反序列化

类对象

注意:也要了解ChildItemCollection类,这是一篇很好的文章,其中对XML的序列化具有完整的父子关系。您可以在这里C# Parent/child relationship and XML serialization

进行检查
[XmlRoot("root")]
public class Apartment
{
    public Apartment()
    {
        this.Children = new ChildItemCollection<Apartment,ApartmentComponent>(this);
    }

    [XmlAttribute("id")]
    public string Id { get; set; }

    [XmlAttribute("name")]
    public string Name { get; set; }

    [XmlElement("ApartmentComponent")]
    public ChildItemCollection<Apartment,ApartmentComponent> Children { get; private set; }
}

public class ApartmentComponent : IChildItem<Apartment>,IChildItem<ApartmentComponent>
{
    public ApartmentComponent()
    {
        this.Children = new ChildItemCollection<ApartmentComponent,ApartmentComponent>(this);
    }

    [XmlAttribute("id")]
    public string Id { get; set; }

    [XmlAttribute("name")]
    public string Name { get; set; }

    [XmlElement("ApartmentComponent")]
    public ChildItemCollection<ApartmentComponent,ApartmentComponent> Children { get; private set; }

    [XmlIgnore]
    public Apartment ParentApartment { get; internal set; }

    Apartment IChildItem<Apartment>.Parent
    {
        get
        {
            return this.ParentApartment;
        }
        set
        {
            this.ParentApartment = value;
        }
    }

    [XmlIgnore]
    public ApartmentComponent ParentComponent { get; internal set; }
    ApartmentComponent IChildItem<ApartmentComponent>.Parent
    {
        get
        {
            return this.ParentComponent;
        }
        set
        {
            this.ParentComponent = value;
        }
    }
}

实施

XmlSerializer serializer = new XmlSerializer(typeof(List<Apartment>),new XmlRootAttribute("root"));
        using (FileStream fileStream = new FileStream("XMLFile1.xml",FileMode.Open))
        {
            var result = (List<Apartment>)serializer.Deserialize(fileStream);
        }

阶段2:拼合为平面数据。
这非常复杂,我可以采用这种方法。但希望还有其他更好的选择。

类对象

public class ResultItem
{
    public string Id { get; set; }
    public string Value { get; set; }
    public string ParentId { get; set; }
    public string ParentValue { get; set; }
}

实施

 XmlSerializer serializer = new XmlSerializer(typeof(List<Apartment>),FileMode.Open))
        {
            var result = (List<Apartment>)serializer.Deserialize(fileStream);
            var items = result.Select(item => new ResultItem {
                Id = item.Id,Value = item.Name
            }).ToList();

            result.ForEach(apartment =>
            {
                apartment.Children.ToList().ForEach(component => {
                    setItemResult(component,items);
                });
            });

            dataGridView1.DataSource = items;
        }

private void setItemResult(ApartmentComponent apartmentComponent,List<ResultItem> items)
    {
        if (apartmentComponent.Children.Count > 0)
        {
            apartmentComponent.Children.ToList().ForEach(component => {
                setItemResult(component,items);
            });
        }

        var item = new ResultItem
        {
            Id = apartmentComponent.Id,Value = apartmentComponent.Name
        };

        var parentApartment = apartmentComponent.ParentApartment;
        var parentComponent = apartmentComponent.ParentComponent;

        if (parentApartment != null)
        {
            item.ParentId = parentApartment.Id;
            item.ParentValue = parentApartment.Name;
        }

        if (parentComponent != null)
        {
            item.ParentId = parentComponent.Id;
            item.ParentValue = parentComponent.Name;
        }

        items.Add(item);
    }

输出:
enter image description here
祝您编程愉快,加油!