【问题标题】:Read Parent nodes only from XML using LINQToXML使用 LINQToXML 仅从 XML 读取父节点
【发布时间】:2010-03-30 11:44:48
【问题描述】:

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

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

【问题讨论】:

    标签: c# linq linq-to-xml


    【解决方案1】:

    使用Elements 方法代替Descendants

    改变这个:

    from Committee in xDocument.Descendants("Committee")
    

    到这里:

    from Committee in xDocument.Elements("Committee")
    

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多