views:

210

answers:

1

I have the following XML Document being loaded into C# Silverlight:

<parent>
    <son name="Jim">
        <grandson>Billy</grandson>
        <granddaughter>Sue</granddaughter>
    </son>
    <daughter name="Sally">
    </daughter> 
</parent>

I'd like to do a LINQ query so that I query parent and get a list of "son" and "daughter" nodes only. When I get to a node of type "son", I want to do another query for its own children.

I've tried this:

 IEnumerable<XElement> Children =
                    from childNode in parents.Descendants()
                    select (XElement)childNode ;

foreach(XElement childNode in Children){
// other code 
}

but that gives me everything (son, daughter, grandson, granddaughter).

What I'd like to do is something like this:

  foreach(XElement childNode in Children){
    switch(childNode.Name.ToString()){
         case "son": 
            // look for "grandson" and "granddaughter" as children of "son" now
            break;
        case "daughter":
           // don't look for anything
           break;
        }
    }

So Basically, I only want the first level of children returned in the query, and I will query for the rest later on.

I'm not sure if it should be done in the original LINQ query, in the foreach condition, or what. I don't have control over the XML document format so I can't change it to something better. Thanks!

+2  A: 

If I understand your question correctly you need to use the Elements function:

            var sons_qry = from son in parents.Elements()
                      select son;

            var grandsons_qry = from grandson in sons_qry.Descendants()
                                select grandson;
bruno conde
that worked! Exactly what I needed. Thank you!
nerdabilly