Click here to Skip to main content
15,885,720 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Is there a way to convert/parse a KML file's coordinates into a format (CSV or XML) that I could later use to import into other programs.

I have polygons in KML files and I'm trying to reuse the coordinates with other programs in different formats.

In my KML file I have coordinates that look like this.

<coordinates>-86.36762,37.31916,0 -86.43890,37.31916,0 -88.96934,32.11572,0 -84.51434,32.68596,0 -82.87490,35.85792,0 -86.36762,37.31916,0

How do I search the KML file and convert the coordinates to a format like this

-86.36762,37.31916,0
-86.43890,37.31916,0
-88.96934,32.11572,0
-84.51434,32.68596,0
-82.87490,35.85792,0
-86.36762,37.31916,0

and save it in a CSV using C#?

Any help would be much appreciated. I'm able to find ways to convert CSV to KML no problem but what about the other way around.

Thanks
Posted

1 solution

If the requirement is to break the set of coordinates into separate lines, then the Replace method of Regex class can be used to replace the spaces which are not preceded by or followed by a comma as shown below:
C#
string kmlInput = @"-86.36762, 37.31916 , 0 -86.43890,37.31916,0 -88.96934,32.11572,0 -84.51434,32.68596,0 -82.87490,35.85792,0 -86.36762,37.31916,0 ";
    string csvOutput = Regex.Replace(kmlInput,
                    @"(?<=[^,]+)\s+(?=[^,]+)","\n",
                    RegexOptions.CultureInvariant);
    Console.WriteLine (csvOutput);

//csvOutput
//-86.36762, 37.31916 , 0
//-86.43890,37.31916,0
//-88.96934,32.11572,0
//-84.51434,32.68596,0
//-82.87490,35.85792,0
//-86.36762,37.31916,0
 
Share this answer
 
Comments
mzrax 31-May-12 9:19am    
VJ Reddy

Thanks

I've taken what you've done to look like this.

string filePath = @"C:\test.csv";
string kmlInput = @"-86.36762, 37.31916 , 0 -86.43890,37.31916,0 -88.96934,32.11572,0 -84.51434,32.68596,0 -82.87490,35.85792,0 -86.36762,37.31916,0 ";
string csvOutput = Regex.Replace(kmlInput,
@"(?<=[^,]+)\s+(?=[^,]+)", "\n",
RegexOptions.CultureInvariant);
System.IO.StreamWriter objWriter;
objWriter = new StreamWriter(filePath, true);
objWriter.WriteLine(csvOutput);
objWriter.Close();

This is great. I really appreciate it.

Thanks Again.
VJ Reddy 31-May-12 10:36am    
You're welcome and thank you for accepting the solution :)
The kmlInput can be read from the file using
string kmlInput = System.IO.File.ReadAllText(filePath);
provided the file contains the required input
then

csvOutput can be written to file using
System.IO.File.WriteAllText(outFilePath, csvOutput);
umarabbas 14-Nov-12 6:36am    
Good
Maciej Los 31-May-12 9:28am    
Short and to the point, my 5!
VJ Reddy 31-May-12 10:37am    
Thank you, losmac :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900