仅使用LINQToXML从XML读取父节点

时间:2010-03-30 02:35:38

标签: c# linq linq-to-xml

我的XML字符串有父节点“委员会”,里面有另一个子节点“委员会”。当我使用“from committee in xDocument.DescendantsAndSelf("Committee")”时,它也在读取childnode,但我不想读取子节点,我只想读取父节点。

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

2 个答案:

答案 0 :(得分:2)

使用Elements方法代替Descendants

改变这个:

from Committee in xDocument.Descendants("Committee")

对此:

from Committee in xDocument.Elements("Committee")

这将返回当前元素(Committee变量)的子xDocument元素。

答案 1 :(得分:0)

您可以使用XPathSelectElements扩展方法(在System.Xml.Xpath名称空间中)仅选择具有委员会子元素的委员会元素。

var committeeXmls = from Committee in xDocument.XPathSelectElements("Committee[Committee]")
                    ...