题
我有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);
}
}
没有正确的解决方案
其他提示
使用 Elements
方法而不是 Descendants
.
更改此:
from Committee in xDocument.Descendants("Committee")
为此:
from Committee in xDocument.Elements("Committee")
这将返回孩子 Committee
当前元素的元素(xDocument
多变的)。
您可以使用XPathSelectelements扩展方法(在System.xml.XPath名称空间中)仅选择具有委员会子元素的委员会元素。
var committeeXmls = from Committee in xDocument.XPathSelectElements("Committee[Committee]")
...
不隶属于 StackOverflow