下面有XML节点。
...
<ParentNode>
<Node id="2343" name="some name" mode="Some Mode">
//Some child nodes here
</Node>
<Node id="2344" name="some other name" mode="Some Mode">
//Some child nodes here
</Node>
...
</ParentNode>
<ParentNode>
<Node id="2343" name="some name" mode="Some Other Mode">
//Some child nodes here
</Node>
<Node id="2344" name="some other name" mode="Some Mode">
//Some child nodes here
</Node>
</ParentNode>
....我需要的是
id name distinct-mode-count
--------------------------------------------
2343 some name 2
2344 some other name 1我已经试过在下面得到这个。
XElement myXML = XElement.Load(filePath);
IEnumberable<XElement> parentNodes = myXML.Descendants("ParentNode");
var nodeAttributes = parentNodes.Select(le => le.Descendants("Node")
.GroupBy(x => new {
id = x.Attribute("id").Value,
name = x.Attribute("name").Value
}).Select(g => new {
id = g.Key.id,
name = g.Key.name,
distinct_mode_count = // This is where I am stuck
}));我不知道如何在上面的查询中获得distinct_mode_count。
编辑
我需要属性"mode"的不同属性值计数,而不管它们在哪个ParentNode中。
发布于 2015-06-15 09:39:06
假设您希望在具有相同ID/名称的节点中计算不同的“模式”属性值,则只需从组中的每个元素投影到模式,然后获取这些模式的不同顺序,然后计数:
您只需要计算组的数量,还可以使用SelectMany来“夷平”父节点。(或者使用myXml.Descendants("Node")开始。)
给出你想要的结果的简短而完整的例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
class Test
{
static void Main()
{
XElement myXML = XElement.Load("test.xml");
IEnumerable<XElement> parentNodes = myXML.Descendants("ParentNode");
var nodeAttributes = parentNodes
.SelectMany(le => le.Descendants("Node"))
.GroupBy(x => new {
Id = x.Attribute("id").Value,
Name = x.Attribute("name").Value
})
.Select(g => new {
g.Key.Id,
g.Key.Name,
DistinctModeCount = g.Select(x => x.Attribute("mode").Value)
.Distinct()
.Count()
});
foreach (var item in nodeAttributes)
{
Console.WriteLine(item);
}
}
}另一种选择是:
XElement myXML = XElement.Load("test.xml");
var nodeAttributes = myXML
.Descendants("Node")
.GroupBy(...)
// Remaining code as beforehttps://stackoverflow.com/questions/30841856
复制相似问题