[英]c# Remove nodes from xml file irrespective of hierarchy
请看我的演示。 我想删除所有重复的地标节点,而不管层次结构如何。 Linq有可能吗? 删除所有重复节点并另存为新xml文件的最佳方法是什么。
另外请注意,对于演示,我已经创建了一个字符串,否则我将从计算机路径中加载xml文件。
https://dotnetfiddle.net/vAA6Xu
更新资料
var raw = @"<?xml version='1.0' encoding='UTF-8'?><kml xmlns= 'http://www.opengis.net/kml/2.2'>
<Document>
<Folder>
<Placemark>
<name>1</name>
<description>abc</description>
<Point>
<coordinates>102.595626,14.996729</coordinates>
</Point>
</Placemark>
<Placemark>
<name>2</name>
<description>abc</description>
<Point>
<coordinates>102.595626,14.996729</coordinates>
</Point>
</Placemark>
<Placemark>
<name>2</name>
<description>abc</description>
<Point>
<coordinates>102.595626,14.996729</coordinates>
</Point>
</Placemark>
<Placemark>
<name>4</name>
<description>abc</description>
<Point>
<coordinates>102.595626,14.996729</coordinates>
</Point>
</Placemark>
<Folder>
<Placemark>
<name>3</name>
<description>abc</description>
<Point>
<coordinates>102.595626,14.996729</coordinates>
</Point>
</Placemark>
<Placemark>
<name>4</name>
<description>abc</description>
<Point>
<coordinates>102.595626,14.996729</coordinates>
</Point>
</Placemark>
<Placemark>
<name>4</name>
<description>abc</description>
<Point>
<coordinates>102.595626,14.996729</coordinates>
</Point>
</Placemark>
</Folder>
</Folder>
<Placemark>
<name>4</name>
<description>abc</description>
<Point>
<coordinates>102.595626,14.996729</coordinates>
</Point>
</Placemark>
<Placemark>
<name>4</name>
<description>abc</description>
<Point>
<coordinates>102.595626,14.996729</coordinates>
</Point>
</Placemark>
</Document>
</kml>";
编码
var xdoc = XDocument.Parse(raw);
XNamespace ns = "http://www.opengis.net/kml/2.2";
xdoc.Root.Elements(ns+"Document").Elements(ns+"Placemark").GroupBy(i => (string)i).SelectMany(g => g.Skip(1)).Remove();
我想查找所有地标节点并删除重复的节点,而不管层次结构如何
您可以通过将地标节点的值的串联添加到字典中来实现。
如果您在字典中找到该节点的值,则它是重复的,您可以在其上调用.Remove()
。
一种方法:
var raw = "yourxmlhere";
var xdoc = XDocument.Parse(raw);
XNamespace ns = "http://www.opengis.net/kml/2.2";
Dictionary<string,bool> dictionary = new Dictionary<string,bool>();
var descendants = xdoc.Root.Descendants(ns + "Placemark").ToList();
foreach(var node in descendants){
string key = string.Join("", node.Elements().Select(el => el.Value));
if(dictionary.ContainsKey(key))
node.Remove();
else
dictionary.Add(key, true);
}
//at this point your xdoc only contains unique Placemark nodes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.