简体   繁体   中英

How to use Linq2Xml to remove nodes with identical value?

I've got a xml file which is like below

<?xml version="1.0" encoding="utf-8"?>
<front>
    <mtext>a+l</mtext>
    <keyword-group type="Fis">
        <kwd>Tove</kwd>
        <kwd>Jani</kwd>
        <kwd>Reminder</kwd>
    </keyword-group>
    <keyword-group type="Lio">
        <kwd>Saio</kwd>
        <kwd>Tove</kwd>
        <kwd>EMP</kwd>
        <kwd>CSTC</kwd>
    </keyword-group>
    <keyword-group type="LioFree">
        <kwd>Iola</kwd>
        <kwd>Jani</kwd>
        <kwd>Priest</kwd>
    </keyword-group>
    <title>Iatola of rocknrolla</title>
</front>

I want to remove all <kwd> nodes having the same value while keeping the first one. So the output xml file should look like this

<?xml version="1.0" encoding="utf-8"?>
<front>
    <mtext>a+l</mtext>
    <keyword-group type="Fis">
        <kwd>Tove</kwd>
        <kwd>Jani</kwd>
        <kwd>Reminder</kwd>
    </keyword-group>
    <keyword-group type="Lio">
        <kwd>Saio</kwd>
        <kwd>EMP</kwd>
        <kwd>CSTC</kwd>
    </keyword-group>
    <keyword-group type="LioFree">
        <kwd>Iola</kwd>
        <kwd>Priest</kwd>
    </keyword-group>
    <title>Iatola of rocknrolla</title>
</front>

I did

XDocument xdoc=XDocument.Load(@"C:\docm\12345.xml");

            xdoc.Descendants("kwd")
                .GroupBy(g => (string)g.Value)
                .Where(g => g.Count() > 1)
                .SelectMany(g => g.Take(1))
                .Remove();

But the xml file remains unchanged...what did I miss?

Try this

XDocument xdoc=XDocument.Load(@"D:\test\12345.XML",LoadOptions.PreserveWhitespace);

xdoc.Descendants("kwd")
 .GroupBy(g => (string)g.Value.ToLower())
 .Where(g => g.Count() > 1)
 .SelectMany(g => g.Skip(1))
 .Remove();

xdoc.Save(@"D:\test\12345.XML",SaveOptions.DisableFormatting);

This will work even when the values of the node kwd have different cases. If you don't want to preserve whitespaces ignore LoadOptions and SaveOptions part.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM