How can I copy all KmlNodes (and children nodes) from one KmlDocument to another KmlDocument

237
2
Jump to solution
10-09-2020 03:55 PM
justinfernandes
New Contributor II
IEnumerable<Layer> layers_to_export = this.ViewModel.Map.OperationalLayers.Where(I => I.Name.Equals(activeLayerName)).ToList();

foreach (var layer_to_export in layers_to_export)
{
if (layer_to_export.Name.EndsWith("kmz") || layer_to_export.Name.EndsWith("KMZ"))
{

var kml_layer = layer_to_export.Clone() as KmlLayer;
await kml_layer.LoadAsync();

KmlDocument kmlDoc = new KmlDocument();


KmlDataset kmlDataset = new KmlDataset(kmlDoc);




foreach (var node in kml_layer.Dataset.RootNodes)
{

kmlDoc.ChildNodes.Add(node);
}

}
}

When this code is run, an exception is thrown at line 22: "kmlDoc.ChildNodes.Add(node);".  

Exception:  Esri.ArcGISRuntime.ArcGISRuntimeException: 'Object already owned.: Already owned.'

I have found that a similar exception is thrown (from some google searching) when attempting to add a reference of an object that is already being "used" somewhere else.  In this case i presume that the node being Add() to the ChildNodes of the kmlDoc is already owned by the kml_layer  object, therefore it cannot be added.

I am going down the path of recreating everything in the kml from scratch via parsing the kml manually. I feel like this could be done with much less code...but i havent been able to figure it out.

Thank you.

0 Kudos
2 Solutions

Accepted Solutions
DominiqueBroux
Esri Frequent Contributor

A KML node can't belong to multiple containers such as KML folders or KML documents.
Before adding a node to a new document you have to remove it from its initial document.

View solution in original post

TonyWakim
Esri Contributor

Justin,

Have you tried using KmlNode.SaveAsAsync()? 

 KmlNode.SaveAsAsync Method 

View solution in original post

2 Replies
DominiqueBroux
Esri Frequent Contributor

A KML node can't belong to multiple containers such as KML folders or KML documents.
Before adding a node to a new document you have to remove it from its initial document.

View solution in original post

TonyWakim
Esri Contributor

Justin,

Have you tried using KmlNode.SaveAsAsync()? 

 KmlNode.SaveAsAsync Method 

View solution in original post