Have you ever had one of those days when you've dug a hole but your so deep in now that the only option is to keep on digging and see where you come out? I thought just for giggles in the latest component I'm writing to use LINQ to XML because it was about time I saw what all the hooplah was about.
The Problem: I am generating an XML tree to represent a 'collection' of series on a graph, each series can have children a child of a series 'means' that this series of points(to be graphed) is based upon the parent series. So I create my XML as a ruleset and then pass it to a drawing routine that 'should' traverse the tree and draw them in this order i.e. no child gets rendered before its parent.
My XML is programatically created. an example looks like this (not 100% sure I'm doing this right either)
<Chart>
<Chart_Config>
<Color Color="white" />
<Panels Panel="1" /开发者_如何学Python>
</Chart_Config>
<Series ID="0">
<Name>1154.close</Name>
<ID>0</ID>
<IndID>-1</IndID>
<PID>0</PID>
<iType>0</iType>
<Parent>0</Parent>
<Series ID="1">
<Name>1.Indicator</Name>
<ID>1</ID>
<IndID>0</IndID>
<PID>0</PID>
<iType>0</iType>
<Parent>1154.close</Parent>
</Series>
<Series ID="2">
<Name>2.Indicator</Name>
<ID>2</ID>
<IndID>0</IndID>
<PID>0</PID>
<iType>0</iType>
<Parent>1154.close</Parent>
</Series>
<Series ID="3">
<Name>3.Indicator</Name>
<ID>3</ID>
<IndID>0</IndID>
<PID>0</PID>
<iType>0</iType>
<Parent>1154.close</Parent>
</Series>
</Series>
</Chart>
The above xml is a little dodgy but the point is in this case I have 1 series (id = 0) that has 3 series as children and thus 3 series based upon ID=0 series.
The question is what LINQ commands must I use to get ALL the <series>
nodes out in order they went in I.e. from the root out to the leaves.
the Code I have only gets out the first series node not its children I cant get my head around this LINQ syntax or concepts.
var result = from e in ChartRule.Elements("Series")
select e;
Any help appreciated I expect this is quite straight forward if you have any clue at all ;-)
If you need to get all Series elements you can use Descendants(), which is equivalent to "//Series" xpath expression:
from e in ChartRule.Descendants("Series")
select e
Then you can check parent's data programatically...
Descendants() : Returns a filtered collection of the descendant elements for this document or element, in document order. Only elements that have a matching XName are included in the collection.
That's what you need as pointed out by mamoo.
I would rather write it like this :
from e in ChartRule.Descendants()
.Where(x => x.Name.LocalName == "Series")
select e
This would avoid namespace conflicts in case you would get this data from a webservice for example.
精彩评论