Question

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

No correct solution

OTHER TIPS

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
scroll top