使用XML.LINQ(C#)帮助读取递归XML

时间:2011-03-17 03:32:34

标签: c# xml linq recursion

我刚刚开始使用LINQ,我在理解如何从XML文件中递归读取时遇到了一些问题

如果我有类似于

的XML
> <ProjectTemplates>
>   <ProjectTemplate Name="Standard">
>         <DeliverableTemplates>
>           <DeliverableTemplate Name="Each Deliverable">
>             <DependantDeliverables>
>               <DeliverableTemplate Name="Can Have a Collection">
>                 <DependantDeliverables>
>                   <DeliverableTemplate Name="of dependant deliverables">
>                     <DependantDeliverables>
>                       <DeliverableTemplate Name="recursively">
>                         <DependantDeliverables />
>                       </DeliverableTemplate>
>                     </DependantDeliverables>
>                   </DeliverableTemplate>
>                 </DependantDeliverables>
>               </DeliverableTemplate>
>             </DependantDeliverables>
>           </DeliverableTemplate>
>         </DependantDeliverables>
>       </DeliverableTemplate>
>     </DependantDeliverables>
>   </DeliverableTemplate>
> </ProjectTemplates>

我正在尝试将其读入几个非常简单的类

internal class Project
{
    public string Name;
    public List<Deliverable> Deliverables;
}
internal class Deliverable
{
    public string Name;
    public List<Deliverable> DependantDeliverables;

    public Deliverable()
    {
        DependantDeliverables = new List<Deliverable>();
    }
}

但我真的不确定该如何去做。就我而言

var xmlProjects = XElement.Load(XMLPath);
var projecttemplates =
(
    from el in xmlProjects.Elements("ProjectTemplates").Elements("ProjectTemplate")
    select new Project
    {
        Name = el.Attribute("Name").Value,
        Deliverables =
        (
            from elDeliverables in el.Elements("DeliverableTemplates").Elements("DeliverableTemplate")
            select new Deliverable
            {
                Name = elDeliverables.Attribute("Name").Value,
                DependantDeliverables = new List<Deliverable>()   
            }
        ).ToList<Deliverable>()
    }
).ToList<Project>();

我在构建DependantDeliverables列表时遇到了问题。我甚至不确定我是否可以像这样单一的陈述。

有人可以帮忙吗?

杰森

1 个答案:

答案 0 :(得分:1)

我会更改Deliverable类,以便其构造函数接收与给定XElement对应的<DeliverableTemplate>。然后,该构造函数将负责遍历XElement,查找子项,填充List&lt;&gt;,并调用其他构造函数,进一步传入更多XElements,直到您到达并解析所有节点。