Help reading recursive XML using XML.LINQ (C#)
I've just started using LINQ and I'm having a couple of problems understanding how to read recursively from an XML file
If I have XML similar to
> <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>
And I'm trying to read this into a couple of really simple classes
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>();
}
}
But I'm really not sure how to go about it. This is as far as I've got
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").Eleme开发者_运维知识库nts("DeliverableTemplate")
select new Deliverable
{
Name = elDeliverables.Attribute("Name").Value,
DependantDeliverables = new List<Deliverable>()
}
).ToList<Deliverable>()
}
).ToList<Project>();
I'm having problems building the list of DependantDeliverables. I'm not even sure whether I can do it as a single statement like this.
Can someone please help?
Jason
I would change the Deliverable
class so that its constructor takes in the XElement
corresponding to a given <DeliverableTemplate>
. That constructor will then be responsible for traversing the XElement, looking for children, populating the List<>, and invoking further constructors further passing in more XElements until you've reached and parsed all your nodes.
精彩评论