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.

  <CommitteeName>PPMS Staff</CommitteeName>
  <CommitteeName>PPMS </CommitteeName>

     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);

No correct solution


Use the Elements method instead of Descendants.

Change this:

from Committee in xDocument.Descendants("Committee")

To this:

from Committee in xDocument.Elements("Committee")

This will return the child Committee elements of the current element (xDocument variable).

You could use the XPathSelectElements extension method (in the System.Xml.Xpath namespace) to select only those Committee elements that have a Committee child element.

var committeeXmls = from Committee in xDocument.XPathSelectElements("Committee[Committee]")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow