使用LINQ to XML如何根据元素的值对其进行分组
本文关键字:元素 to LINQ XML 何根 使用 | 更新日期: 2023-09-27 18:24:54
下面是我的xml文件的结构:
<adlibXML>
<recordList>
<record priref="1" selected="False">
<collection>TEXTILES</collection>
<someotherelements>xyz</someotherelements>
</record>
<record priref="2" selected="False">
<collection>CERAMICS</collection>
<someotherelements>xyz</someotherelements>
</record>
<record priref="3" selected="False">
<collection>PAINTING</collection>
<someotherelements>xyz</someotherelements>
</record>
<record priref="4" selected="False">
<collection>TEXTILES</collection>
<someotherelements>xyz</someotherelements>
</record>
</recordList>
我使用一些API从供应商的数据库中获取这个xml文件。我的新数据库中有三个表,目录,收藏和文物。我想根据集合元素的值(如"TEXTILES"、"ERAMICS"等)和一个计数器变量对其进行分组,以计算我拥有的集合数量。使用它我可以创建collectionID&collectionTitle在我的Collection表中动态显示。
我无法解决它。到目前为止,我只做了以下代码:
var getcontent = from record in xmldoc.Descendants("record")
//this group by doesn't work
group record by record.Element("collection")
select record.Element("collection").Value;
foreach (var node in getcontent)
{
Response.Write("Collection: " + node + "<br/>");
}
尝试以下操作:
var groups = from record in xmldoc.Descendants("record")
group record by (string)record.Element("collection") into g
select new {
key = g.Key,
count = g.Count()
}
foreach (var group in groups)
{
Response.Write("Collection " + group.key + " has " + group.count + " member(s).");
}