Omanshu Chaurasia
Omanshu Chaurasia

Reputation: 161

How do I find duplicates in XML if an element contains value in C#?

I have a XML:

<root>
<p>This is a Value</p>
<p>This is a Value</p>
<p>This is a Value</p>
<p>This is a Value</p>
<p>This is a Value</p>
<p>This is a Value</p>
<h3>Another Value</h3>
<h3>Another Value</h3>
<h3>Another Value</h3>
<h3>Another Value</h3>
<h3>This is Another Value</h3>
</root>

I want to find duplicate values. So, I did this:

var valueDuplicate = xdoc.Descendants().Where(n => n.Name.LocalName == "p" || n.Name.LocalName == "pw" ||
                                                       n.Name.LocalName == "plt" || n.Name.LocalName == "psf")
                             .GroupBy(x => x.Value).Where(g => g.Count() > 1)
                             .Select(g => new { ElementValue = g.Key, Count = g.Count() }).ToList();
string s = string.Join(Environment.NewLine, valueDuplicate.Select(t => "Value: " + t.ElementValue.Trim() + "- "
                                                                                        + t.Count + " times."));

This finds the duplicate values, but it does not show <h3>This is Another Value</h3> as a duplicate. I want to find all elements that contain the value as well.

Upvotes: 0

Views: 1377

Answers (2)

AmirNorsou
AmirNorsou

Reputation: 1131

XDocument xdoc = XDocument.Parse(xml);
var values = xdoc.Descendants().Select(x => x.Value);
var valueDuplicate = xdoc.Descendants().Select(r => new
 {
  el = r,
  value = values.FirstOrDefault(c => r.Value.Contains(c) || r.Value == c)
 }).GroupBy(x => x.value, x => x.el).Where(x => x.Count() > 1).ToList();

string s = string.Join(Environment.NewLine, valueDuplicate.Select(t => "Value: " + t.Key.Trim() + "- " + t.Count() + " times."));

Upvotes: 1

Bhavin Tanna
Bhavin Tanna

Reputation: 22

XDocument XDocument = XDocument.Parse(MyXmlFile);
        var grouped = XDocument.Descendants("P").GroupBy(x => x.Value).Where(g => g.Count() > 1);
        foreach (var groupItem in grouped)
        {
            foreach (var item in groupItem)
            {
                Console.WriteLine(item);
            }
        }

Upvotes: 0

Related Questions