首先需要有基本的经纬度文件
/// <summary>/// 保存kml文件/// </summary>/// <param name="overlayname"></param>private void SaveKml(string overlayname){string filePath = FilePaths.Find(a => a.Contains(overlayname.Trim()));List<string[]> latlngs = new List<string[]>();ReadFormatTxt(filePath, ref latlngs);//读格式的文件返回经纬度filePath = filePath.Substring(0, filePath.LastIndexOf(".")) + ".kml";string s = "";foreach (string[] ss in latlngs){s += string.Format("{0},{1},{2}", ss[0], ss[1], 0) + " ";}if (!string.IsNullOrEmpty(s)){ SaveKml(filePath, s); }}private void SaveKml(string filepath, string xml){//生成KML文件,注意大小写FileStream fs = new FileStream(filepath, FileMode.Create);XmlTextWriter w = new XmlTextWriter(fs, Encoding.UTF8);// 开始文档w.Formatting = System.Xml.Formatting.Indented;w.WriteStartDocument();w.WriteStartElement("kml", "http://www.opengis.net/kml/2.2");//开始一个元素w.WriteStartElement("Document");//添加子元素w.WriteElementString("name", "Paths");w.WriteElementString("description", "Examples of paths.");w.WriteStartElement("Style");//向先前创建的元素中添加一个属性w.WriteAttributeString("id", "yellowLineGreenPoly");w.WriteStartElement("LineStyle");w.WriteElementString("System.Drawing.Color", "7f00ffff");w.WriteElementString("width", "4");w.WriteEndElement();w.WriteStartElement("PolyStyle");w.WriteElementString("System.Drawing.Color", "7f00ffff");w.WriteEndElement();// 关闭style元素w.WriteEndElement();w.WriteStartElement("Placemark");w.WriteElementString("name", "Absolute Extruded");w.WriteElementString("description", "Transparent green wall with yellow outlines");w.WriteElementString("styleUrl", "#yellowLineGreenPoly");w.WriteStartElement("LineString");w.WriteElementString("extrude", "1");w.WriteElementString("tessellate", "1");w.WriteElementString("altitudeMode", "clampedToGround");w.WriteStartElement("coordinates");// 将路径坐标写在这里w.WriteString(xml);// 关闭所有元素w.WriteEndDocument();// 关闭流w.Close();fs.Close();}
这句比较重要,可以把xml文件从一行的形式,改成正常的多行形式
xmlWriter.Formatting = System.Xml.Formatting.Indented;
