0
<Automobiles>
  <Cars>
    <YearofMfr></YearofMfr>
    <Mileage></Mileage>
    <MeterReading></MeterReading>
    <Color></Color>
    <Condition></Condition>
  </Cars>
  <Cars>
    <YearofMfr></YearofMfr>
    <Color></Color>
    <Condition></Condition>
  </Cars>
</Automobiles>

How can I get an element which has all the child elements. To explain in detail. I have above xml. From this I want to retrieve single node which has all the child nodes. If you see in the second node some information is missing. I tried doing this.

var nodes = from nodeElements in doc.Descendants().FirstOrDefault().Elements()
                 where doc.Descendants().Count()==5
                select nodeElements;

I need a single node as output which has 5 child elements.

<Cars>     
<YearofMfr></YearofMfr>     
<Mileage></Mileage>     
<MeterReading></MeterReading>     
<Color></Color>     
<Condition></Condition>   
</Cars>
Sajid
  • 81
  • 2
  • 10

1 Answers1

5

I suggest you select your count from nodeElements.Descendants instead:

var nodes = (from nodeElements in doc.Root.Elements()
            where nodeElements.Descendants().Count()==5
            select nodeElements).FirstOrDefault();

Updated to reflect the comment below and the comment to your original question.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • Thanks a ton for responding super fast. Daniel's response worked. StackOverFlow Rocks!!! – Sajid Feb 17 '11 at 14:09
  • If I use XDocument as the source object(i.e. doc) the above example is working fine. But its returning null if I use XElement. Sorry for troubling you again... – Sajid Feb 17 '11 at 15:37
  • I have added a question regarding "finding duplicate xelements" here. http://stackoverflow.com/questions/5076772/find-duplicate-xelements. @daniel-hilgarth Please helpout. – Sajid Feb 22 '11 at 12:32
  • I guess there is a difference between querying XDocument & XElement.When I used XDocument as source the below query worked. var nodes = (from nodeElements in doc.Root.Elements() where nodeElements.Descendants().Count()==5 select nodeElements).FirstOrDefault(); When I changed the source to XElement. I had to change to IEnumerable nodes = (from nodeElements in payLoad.DescendantsAndSelf().Elements() where nodeElements.Descendants().Count() == 5 select nodeElements); Main difference here abv 2 queries is doc.Root.Elements() and payLoad.DescendantsAndSelf().Elements(). – Sajid Feb 22 '11 at 12:51