gpt4 book ai didi

c# - 使用 LINQToXML 仅从 XML 读取父节点

转载 作者:太空宇宙 更新时间:2023-11-03 11:49:07 25 4
gpt4 key购买 nike

我有一个 XML 字符串,它有父节点“Committee”,里面有另一个子节点“Committee”。当我使用“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);
}
}

最佳答案

使用 Elements 方法代替 Descendants

改变这个:

from Committee in xDocument.Descendants("Committee")

对此:

from Committee in xDocument.Elements("Committee")

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

关于c# - 使用 LINQToXML 仅从 XML 读取父节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2542534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com