我一直在 Linqpad 上玩,试图做到这一点,但我一直在想念。考虑以下:
//<SpeciesSizes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
// < SpeciesSize >
// < DisplayCode > CAT </ DisplayCode >
// < EnglishName > Wolffishes(= Catfishes) nei </ EnglishName >
// < State > FRE </ State >
// < Presentation > BMS </ Presentation >
// < Freshness > SO </ Freshness >
// < Size > 9 </ Size >
// < Description > Species not included in the common marketing standards</Description>
// </SpeciesSize>
// <SpeciesSize>
// <DisplayCode>CAT</DisplayCode>
// <EnglishName>Wolffishes(= Catfishes) nei </ EnglishName >
// < State > FRE </ State >
// < Presentation > FIL </ Presentation >
// < Freshness > SO </ Freshness >
// < Size > 9 </ Size >
// < Description > Species not included in the common marketing standards</Description>
// </SpeciesSize>
// < SpeciesSize >
// < DisplayCode > FLE </ DisplayCode >
// < EnglishName > European flounder </ EnglishName >
// < State > FRE </ State >
// < Presentation > GUT </ Presentation >
// < Freshness > E </ Freshness >
// < Size > 1 </ Size >
// < Description > According to AnnexII of Council R. 2406 / 96 </ Description >
// </ SpeciesSize >
// < SpeciesSize >
// < DisplayCode > GUX </ DisplayCode >
// < EnglishName > Gurnards, searobins nei</EnglishName>
// <State>FRO</State>
// <Presentation>ROE</Presentation>
// <Freshness>SO</Freshness>
// <Size>9</Size>
// <Description>Species not included in the common marketing standards</Description>
// </SpeciesSize>
//</SpeciesSizes>
static string path = @"C:\Users\dom\Documents\Speciescrossreference.xml";
void Main()
{
XDocument doc = XDocument.Load(path);
var names = from n in doc.Root.Descendants("SpeciesSizes")
group n by n.Element("SpeciesSize") into g
select new {
name = g.Element("EnglishName").Distinct().ToList()
};
names.Dump();
}
大约有 4000 个<SpeciesSize>
元素,其中大约有 150 个独特的英文名称。
我已经在 SO 上阅读了各种答案,并从中吸取了一些东西来拼凑我在这里的内容,但显然我未能理解这些答案中展示的所有语法。
有人能告诉我我做错了什么,以便我以后能够构造其他查询(针对相同的 xml),这些查询可能涉及对不同元素进行分组。
鉴于代码示例顶部的示例 xml,我将查看 atr 返回以下内容:
如果您的示例中没有空格,您可以使用:
var names = from n in doc.Root.Descendants("SpeciesSize")
group n by n.Element("EnglishName").Value into g
select new
{
name = g.Key
};
更新@CodingYoshi:
是的,没错。如果只是读取名称,您可以执行以下操作:
var names = doc.Root.Descendants("EnglishName")
.Select(item => item.Value)
.Distinct()
.OrderBy(item => item);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句