开发者

How to select distinct xml nodes

开发者 https://www.devze.com 2022-12-25 14:06 出处:网络
How to takedistinct nodes listin XML in c# for example <root> <node1 ss=\"d开发者_StackOverflow中文版1\" ff=\"f1\" gg=\"h1\"/>

How to take distinct nodes list in XML in c#

for example

<root>
<node1 ss="d开发者_StackOverflow中文版1" ff="f1" gg="h1"/>
<node1 ss="d1" ff="f2" gg="h1"/>
<node1 ss="d1" ff="f1" gg="h1"/>
<node1 ss="d2" ff="f1" gg="h1"/>
<node1 ss="d1" ff="f1" gg="h1"/>
<node1 ss="d1" ff="f1" gg="h1"/>
<node1 ss="d2" ff="f1" gg="h1"/>
<node1 ss="d1" ff="f2" gg="h1"/>
</root>

in this XML i will take distinct node and make this xml

<root>
<node1 ss="d1" ff="f1" gg="h1"/>
<node1 ss="d1" ff="f2" gg="h1"/>
<node1 ss="d2" ff="f1" gg="h1"/>
</root>

this xml is sample not real and i look for a solution in global mode for any struct in xml


Various ways you could do that; Muenchian grouping in xslt for example. But in C#, if the xml layout is known and fixed, perhaps the easiest would be:

        var root = XElement.Parse(xml);
        var newRoot = new XElement("root",
            root.Elements("node1").Select(el =>
            new {
                ss = (string)el.Attribute("ss"),
                ff = (string)el.Attribute("ff"),
                gg = (string)el.Attribute("gg"),
            }).Distinct().Select(obj =>
                new XElement("node1",
                    new XAttribute("ss", obj.ss),
                    new XAttribute("ff", obj.ff),
                    new XAttribute("gg", obj.gg))));

If you need something more flexible, an IEqualityComparer<XElement> (for use with .Distinct()) would be more valuable.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号