[英]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.