My requirement is that there should be only one listingagent TAG for each role_type Primary inside each commercial tag.
<deal>
<commercial>
<party></party>
<party>
<role_detail>
<role_type>Primary</role_type>
</role_detail>
<listingagents>
<listingagent>1</listingagent>
<listingagent>2</listingagent>
</listingagents>
</party>
<party>
<role_detail>
<role_type>Secondary</role_type>
</role_detail>
<listingagents>
<listingagent>1</listingagent>
</listingagents>
</party>
<party></party>
</commercial>
<commercial>
</commercial>
<commercial>
</commercial>
</deal>
If there are more than one I need to raise an error.
The code I tried is as follows
var duplicates = doc.Descendants("Commercial")
.Select(c => c.Descendants("listingAgent"))
.GroupBy(c => c.ToString())
.Where(g => g.Count() > 1)
.Select(g => g.First())
.ToList();
if (duplicates.Any(c => c.Count() > 1))
{
//show error
}
If your constraint is that there should be exactly one listingAgent
element within each commercial
element, that's very simple:
var broken = doc.Descendants("commercial")
.Any(c => c.Elements("listingAgent").Count() != 1);
This doesn't ensure that elements are unique though. For example, given that requirement, this XML is fine:
<deals>
<commercial>
<listingAgent>1</listingAgent>
</commercial>
<commercial>
<listingAgent>1</listingAgent>
</commercial>
<commercial>
<listingAgent>1</listingAgent>
</commercial>
<deals>
Each commercial
element here has exactly one listingAgent
child element. They've all got the same value, but that isn't part of the stated requirement. If you want uniqueness, that's a different requirement - and one that could be independent of the number of listingAgent
children. For example, this meets uniqueness but not the "exactly one child" requirement:
<deals>
<commercial>
<listingAgent>1</listingAgent>
<listingAgent>2</listingAgent>
</commercial>
<commercial>
</commercial>
<deals>
See more on this question at Stackoverflow