通过LINQ检查XML中每个子节点的重复值

时间:2016-09-27 13:15:00

标签: c# xml linq

我是新手使用linq特别是linq到xml并且我在尝试迭代结果时遇到了麻烦。我的xml文档有多个同名的节点嵌套在单个父节点中。

示例XML是:

<commercial>
   <listingAgent>1</listingAgent>
   <listingAgent>2</listingAgent>
   <listingAgent>1</listingAgent>
</commercial>  
<commercial>
   <listingAgent>1</listingAgent>
   <listingAgent>2</listingAgent>
   <listingAgent>3</listingAgent>
</commercial> 

因此,对于每个商业广告代码,都应该有唯一的商家信息代码值。如果不是我需要引发错误。

真正的XML非常复杂,这些标签远不是根本。所以我需要遍历这些,然后搜索duplciates

我尝试了以下代码

foreach (XElement e in root.Descendants("listingAgent"))
{
   listerror.Add(e.Value);
}

if(listerror.Count != listerror.Distinct().Count()) 
     Then show error

但是我需要为每个商业广告做这个循环。

1 个答案:

答案 0 :(得分:2)

首先,选择所有商业节点,然后对于每个节点,您可以使用var result= xdoc.Descendants("commercial") .Select(c=>c.Descendants("listingAgent").Select(e=>e.Value)); if(result.Any(e=>e.Count()!= e.Distinct().Count()) { //error } 获取代理值列表,这样您将获得列表列表,最后您可以应用相同的条件尝试之前,但现在为每个代理商列表:

import re

rx = re.compile(r'^(?P<interesting>.+?)-(?P<uid>\b\w{8}-(?:\w{4}-){3}\w{12}\b)(?P<junk>.+)$', re.MULTILINE | re.VERBOSE)

test_str = u"00000 Gin-12-a19ea68e-64bf-4471-b4d1-44f6bd9c1708-62fa6ae2-599c-4ff1-8249-bf6411ce3be7-83930e63-2149-40f0-b6ff-0838596a9b89 Kin\n00000 Gin-a19ea68e-64bf-4471-b4d1-44f6bd9c1708 Kin\ntest123 test 12345678-1234-1234-1234-123456789012 junk afterwards\n"
tmp = re.match(rx, test_str)
print(tmp.groupdict()["interesting"])