I have a XML like this:
<rewriteMaps>
<rewriteMap name="RewritesInSightContentaltecNL">
<add key="/tata" value="/productdetails.aspx?id=1628" />
<add key="/tata" value="/productdetails.aspx?id=1628" />
<add key="/marc" value="/productdetails.aspx?id=1626" />
<add key="/marc" value="/productdetails.aspx?id=1626" />
<add key="/marc" value="/productdetails.aspx?id=1626" />
<add key="/henk" value="/productdetails.aspx?id=162996" />
<add key="/henk" value="/productdetails.aspx?id=1aa6" />
<add key="/tata" value="/productdetails.aspx?id=1628" />
<add key="/tata" value="/productdetails.aspx?id=1628" />
<add key="/marc" value="/productdetails.aspx?id=1626" />
<add key="/marc" value="/productdetails.aspx?id=1626" />
<add key="/aaaa" value="/productdetails.aspx?id=xxxx" />
</rewriteMap>
</rewriteMaps>
From which I want to remove duplicate values base on the "key" attribute"
So I want to end up with:
<add key="/tata" value="/productdetails.aspx?id=1628" />
<add key="/marc" value="/productdetails.aspx?id=1626" />
<add key="/henk" value="/productdetails.aspx?id=162996" />
<add key="/aaaa" value="/productdetails.aspx?id=xxxx" />
Any help greatly appreciated.
Use Remove extension method.This method will remove all selected nodes from document. Try this code.
xdoc.Root.Elements("add")
.GroupBy(s => (string)s.Element("value"))
.SelectMany(g => g.Skip(1)) // select all nodes from group except first one
.Remove();
XElement rewriteMaps = XElement.Parse(xmlToParse);
var distinct data= rewriteMaps.Descendants("rewriteMap")
.Elements()
.GroupBy(x=> new { key = (string)x.Attribute("key"), value = (string)x.Attribute("value")})
.Select(x=> x.FirstOrDefault());
This will give you
<add key="/tata" value="/productdetails.aspx?id=1628" />
<add key="/marc" value="/productdetails.aspx?id=1626" />
<add key="/henk" value="/productdetails.aspx?id=162996" />
<add key="/henk" value="/productdetails.aspx?id=1aa6" />
<add key="/aaaa" value="/productdetails.aspx?id=xxxx" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.