Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify Duplicate Nodes in XML Using XPath

Tags:

c#

xml

xpath

I am trying to identify duplicate group nodes in the following XML structure. I need to find all groups with the same name, wherever they are in the tree.

<report>
    <group name="a">
        <group name="1"></group>
        <group name="2"></group>
    </group>
    <group name="b">
        <group name="1"></group>
    </group>
</report>

Similar to this post (How do I identify duplicate nodes in XPath 1.0 using an XPathNavigator to evaluate?) However, I need to identify groups with the same attribute rather than the same node value.

like image 342
user2367250 Avatar asked Jan 14 '23 10:01

user2367250


1 Answers

How about using Linq To xml to find duplicates?

var dubs = XDocument.Parse(xml)
            .Descendants("group")
            .GroupBy(g => (string)g.Attribute("name"))
            .Where(g => g.Count() > 1)
            .Select(g => g.Key);
like image 58
I4V Avatar answered Jan 21 '23 19:01

I4V