How to get tree data with recursive call in Linq?

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
I have xml data from restful service. It is kind of heriarchy tree data. I want to extract the data from xml in following way:
<br/>
XDocument xml = XDocument.Parse(e.Result);<br/>
var dataSource = (from results in xml.Descendants("nodeObject")<br/>
where(int.parse(results.Element("Level").Value.ToString()) ==1)<br/>
select new nodeObject<br/>
{<br/>
Name = results.Element("Name").Value.ToString(),<br/>
Level = int.parse(results.Element("Level").Value.ToString()),<br/>
nodeChildren = this.GetChildren(results)<br/>
});<br/>
this.dataTree.ItemsSource = dataSource.ToList();<br/>
<br/>
<br/>
<br/>
private IEnumerable<nodeObject> GetChildren(XElement parent)<br/>
{<br/>
return (from results in parent.Descendants("nodeObject")<br/>
where(int.parse(results.Element("Level").Value.ToString()) == int.parse(parent.Element("Level").Value.ToString()) +1)<br/>
select new nodeObject<br/>
{<br/>
Name = results.Element("Name").Value.ToString(),<br/>
Level = results.Element("Level").Value.ToString(),<br/>
nodeChildren = this.GetChildren(results)<br/>
}).ToList<nodeObject>();<br/>
}<br/>
<br/>
Internal class nodeObject<br/>
{<br/>
<br/>
public string Name { get; set; }<br/>
public int Level{ get; set; }<br/>
public IEnumerable<nodeObject> nodeChildren { get; set; }<br/>
}
But I cant get it in dataSource. It seems only give me top 2 levels data.
Here is xal data sample for this case:
<nodeData><br/>
<nodeObject><br/>
<Name>Node 1</Name><br/>
<Level>1</Level><br/>
<nodeChildren><br/>
<nodeObject><br/>
<Name>Node 1-1</Name><br/>
<Level>2</Level><br/>
<nodeChildren><br/>
<nodeObject><br/>
<Name>Leaf 1-1-1</Name><br/>
<Level>3</Level><br/>
</nodeObject><br/>
<nodeObject><br/>
<Name>Leaf 1-1-2</Name><br/>
<Level>3</Level><br/>
</nodeObject><br/>
<nodeObject><br/>
<Name>Leaf 1-1-3</Name><br/>
<Level>3</Level><br/>
</nodeObject><br/>
<nodeObject><br/>
<Name>schedule 4.pdf</Name><br/>
<Level>3</Level><br/>
</nodeObject><br/>
</nodeChildren><br/>
</nodeObject><br/>
<nodeObject><br/>
<Name>Node 1-2</Name><br/>
<Level>2</Level><br/>
<nodeChildren><br/>
<nodeObject><br/>
<Name>Leaf 1-2-1</Name><br/>
<Level>3</Level><br/>
</nodeObject><br/>
</nodeChildren><br/>
</nodeObject><br/>
</nodeChildren><br/>
</nodeObject><br/>
<nodeObject><br/>
<Name>Node 2</Name><br/>
<Level>1</Level><br/>
<nodeChildren><br/>
<nodeObject><br/>
<Name>Node 2-1</Name><br/>
<Level>2</Level><br/>
<nodeChildren><br/>
<nodeObject><br/>
<Name>Leaf 2-1-1</Name><br/>
<Level>3</Level><br/>
</nodeObject><br/>
</nodeChildren><br/>
</nodeObject><br/>
</nodeChildren><br/>
</nodeObject><br/>
......<br/>
</nodeData> <br/>
<br/>
<br/>


How to resolve it?

<br/>

View the full article
 
Back
Top