这是一个分组示例:
XDocument doc = XDocument.Load("../../XMLFile1.xml");
var groups = from msg in doc.Root.Elements("Msg")
where !((string)msg.Attribute("UserText")).StartsWith("start")
group msg by
msg.ElementsBeforeSelf("Msg").Where(m =>
((string)m.Attribute("UserText")).StartsWith("start")).Last();
foreach (var group in groups)
{
Console.WriteLine("Group starting with {0} has {1} member(s).",
group.Key.Attribute("UserText"), group.Count());
}
使用 XML 输入示例 XMLFile1.xml
<Root>
<Msg UserText="start 0">
</Msg>
<Msg UserText="A">
</Msg>
<Msg UserText="A">
</Msg>
<Msg UserText="start 1">
</Msg>
<Msg UserText="A">
</Msg>
<Msg UserText="start 2">
</Msg>
<Msg UserText="A">
</Msg>
<Msg UserText="A">
</Msg>
<Msg UserText="A">
</Msg>
</Root>
我得到输出
Group starting with UserText="start 0" has 2 member(s).
Group starting with UserText="start 1" has 1 member(s).
Group starting with UserText="start 2" has 3 member(s).