本文介绍了使用Linq to XML(C#)获取disticnt条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 输入XML文件: Input XML File:<?xml version="1.0" encoding="utf-8" ?><TOP> <SUB1 name="AB"> <SUB11 name="CD"> <SUB111> <KV> <key>KEY1</key> <value>1234</value> </KV> <KV> <key>KEY1</key> <value>5678</value> </KV> </SUB111> </SUB11> <SUB11 name="CD"> <SUB111> <KV> <key>KEY1</key> <value>1357</value> </KV> <KV> <key>KEY2</key> <value>2468</value> </KV> </SUB111> </SUB11></SUB1></TOP> 需要提取所有KV元素,但在每个SUB111中都是不同的。预期的字符串输出列表: Need to extract all KV elements but distinct within every SUB111. Expected output list of strings:<key>KEY1</key><value>1234</value><key>KEY1</key><value>1357</value><key>KEY2</key><value>2468</value> 请注意重复的KEY1 in第一个SUB111被淘汰 尝试类似下面的东西,但不成功: Note that duplicate KEY1 in first SUB111 is eliminatedTrying something similar to below, but not successful:IEnumerable<XElement> KVs = null;KVs = (from sub1 in xDoc.XPathSelectElements("SUB1") where (string)sub1.Attribute("name").Value == "AB" from sub11 in sub1.Elements("SUB11") where (string)sub11.Attribute("name").Value == "CD" select sub11).SelectMany(sub111 => sub111.Elements("SUB111").Elements("KV")).ToList(); 预先感谢您的帮助! 问候 S. Vikram Thanks in advance for your help!RegardsS. Vikram推荐答案 string xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?><TOP><SUB1 name=""AB""> <SUB11 name=""CD""> <SUB111> <KV> <key>KEY1</key> <value>1234</value> </KV> <KV> <key>KEY1</key> <value>5678</value> </KV> </SUB111></SUB11> <SUB11 name=""CD""> <SUB111> <KV> <key>KEY1</key> <value>1357</value> </KV> <KV> <key>KEY2</key> <value>2468</value> </KV> </SUB111></SUB11></SUB1></TOP>";XDocument doc = XDocument.Parse(xml);var items = doc.Root.Descendants("SUB111") .SelectMany(s=>s.Descendants("KV") .GroupBy(x=>(string)x.Element("key")) .Select(g=>g.First())) .ToList(); 您可能需要添加您的where条件,但最重要的是您可以按键值进行分组并选择组中的第一项,这将删除重复。You may need to add your where conditions but most important thing is you can group by key value and select the first item of the group, that will remove the duplicates. 在selectMany()之后使用Distinct()。Use Distinct() after selectMany(). 这篇关于使用Linq to XML(C#)获取disticnt条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-27 09:22