我有一个xml文件,如下所示
<?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>
我希望删除具有相同值的所有<kwd>
个节点,同时保留第一个节点。因此输出xml文件应如下所示
<?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>
我做了
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();
但是xml文件保持不变......我错过了什么?
答案 0 :(得分:0)
试试这个
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);
即使节点kwd
的值具有不同的情况,这也会起作用。
如果您不想保留空格,请忽略LoadOptions
和SaveOptions
部分。