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.
精彩评论