Frage

Ich habe eine XML -Zeichenfolge, die übergeordnete Knoten "Komitee" hat, und in diesem anderen Kinderknotenkomitee ist da. Wenn ich benutze "from committee in xDocument.DescendantsAndSelf("Committee")"Es wird auch Childnode gelesen, aber ich möchte keine Kinderknoten lesen, ich möchte nur übergeordnete Knoten lesen.

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

Keine korrekte Lösung

Andere Tipps

Verwenden Sie das Elements Methode statt von Descendants.

Ändere das:

from Committee in xDocument.Descendants("Committee")

Dazu:

from Committee in xDocument.Elements("Committee")

Dies wird das Kind zurückgeben Committee Elemente des aktuellen Elements (xDocument Variable).

Sie können die XPathSelectElements -Erweiterungsmethode (im System.xml.xpath -Namespace) verwenden, um nur die Ausschusselemente auszuwählen, die ein Kindeselement haben.

var committeeXmls = from Committee in xDocument.XPathSelectElements("Committee[Committee]")
                    ...
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top