Read Parent nodes only from XML using LINQToXML

Posted by ItsMeSri on Stack Overflow See other posts from Stack Overflow or by ItsMeSri
Published on 2010-03-30T02:35:38Z Indexed on 2010/03/30 2:43 UTC
Read the original article Hit count: 482

Filed under:

I have XML string that has parent nodes "Committee" and inside that another child node "Committee" is there. When I am using "from committee in xDocument.DescendantsAndSelf("Committee")" it is reading childnode also, but I don't want to read child nodes, I just want to read Parent nodes only.

<Committee>
  <Position>STAFF</Position>
  <Appointment>1/16/2006</Appointment>
  <Committee>PPMSSTAFF</Committee>
  <CommitteeName>PPMS Staff</CommitteeName>
  <Expiration>12/25/2099</Expiration>      
</Committee>
<Committee>
   <Position>STAFF</Position>
  <Appointment>4/16/2004</Appointment>
  <Committee>PMOSSTAFF</Committee>
  <CommitteeName>PPMS </CommitteeName>
  <Expiration>12/25/2099</Expiration>
</Committee>

     XElement xDocument= XElement.Parse(xml);

 var committeeXmls = from Committee in xDocument.Descendants("Committee")
                                select new
                                {
                                    CommitteeName = Committee.Element("CommitteeName"),
                                    Position = Committee.Element("Position"),
                                    Appointment = Committee.Element("Appointment"),
                                    Expiration = Committee.Element("Expiration")
                                };

            int i = 0;
            foreach (var committeeXml in committeeXmls)
            {
                if (committeeXml != null)
                {
                    drCommittee = dtCommittee.NewRow();
                    drCommittee["ID"] = ++i;
                    drCommittee["CommitteeName"] = committeeXml.CommitteeName.Value;
                    drCommittee["Position"] = committeeXml.Position.Value;
                    drCommittee["Appointment"] = committeeXml.Appointment.Value;
                    drCommittee["Expiration"] = committeeXml.Expiration.Value;

                    dtCommittee.Rows.Add(drCommittee);                                        //   educationXml.GraduationDate.Value, educationXml.Major.Value);
                }
            }

© Stack Overflow or respective owner

Related posts about linqtoxml