如果元素包含C#中的值,如何查找XML中的重复项?

时间:2019-05-22 09:53:24

标签: c# .net xml linq

我有一个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>

我想找到重复的值。所以,我这样做了:

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."));

这会找到重复的值,但不会将<h3>This is Another Value</h3>显示为重复的值。我想查找所有包含该值的元素。

2 个答案:

答案 0 :(得分:1)

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."));

答案 1 :(得分:0)

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);
            }
        }