From aec00ecc093be803860c8675cbe1c4c776a7cb4e Mon Sep 17 00:00:00 2001
From: GuLiMmo <2820890765@qq.com>
Date: Tue, 19 Mar 2024 17:49:21 +0800
Subject: [PATCH] update: 新建航线、事件编辑、kmz文件问题修改

---
 src/utils/cesium/kmz.ts |  165 ++++++++++++++++++++++++++++++++++++-------------------
 1 files changed, 108 insertions(+), 57 deletions(-)

diff --git a/src/utils/cesium/kmz.ts b/src/utils/cesium/kmz.ts
index 1c3440f..84d9435 100644
--- a/src/utils/cesium/kmz.ts
+++ b/src/utils/cesium/kmz.ts
@@ -1,10 +1,7 @@
 import axios from 'axios'
 import JsZip from 'jszip'
-import toGeoJson from '@mapbox/togeojson'
-// import Xml2Json from 'xml2json'
-// const xmlJson = new Xml2Json()
 
-const noWmpl: string[] = ['Folder', 'Placemark', 'Point', 'coordinates']
+const noWmpl: string[] = ['Document', 'Folder', 'Placemark', 'Point', 'coordinates']
 
 /**
  * @description: 读取kmz文件解析出kml文件
@@ -73,16 +70,6 @@
   return paramGroup
 }
 
-export const insertChar = (str: string, index: number, char: string) => {
-  if (index > str.length) {
-    return str + char
-  } else if (index < 0) {
-    return char + str
-  } else {
-    return str.slice(0, index) + char + str.slice(index)
-  }
-}
-
 export const getTagNameFromXml = (xmlString: string): string | null => {
   const parser = new DOMParser()
   const xmlDoc = parser.parseFromString(xmlString, 'text/xml')
@@ -94,61 +81,125 @@
 }
 
 // 将xml转为json
-const deepParse = (xmlDoc: Document, tagName: string) => {
-  const xmlObj: { [key: string]: any } = {}
-  const rootDom = xmlDoc.getElementsByTagName(tagName)[0]
-  for (let i = 0; i < rootDom.children.length; i++) {
-    const child = rootDom.children[i]
-    const childName = child.nodeName.replace('wpml:', '')
-    if (child.children.length > 0) {
-      xmlObj[childName] = deepParse(xmlDoc, child.nodeName)
-    } else {
-      if (xmlObj[childName] !== undefined) {
-        if (!Array.isArray(xmlObj[childName])) {
-          xmlObj[childName] = [xmlObj[childName]]
+const deepParse = (
+  xml:
+    | {
+        nodeType: number
+        childNodes: string | any[]
+        nodeValue: string
+        attributes: { length: number; item: (arg0: number) => any }
+      }
+    | any,
+) => {
+  let obj: any = {}
+  // 如果是文档节点,遍历其子节点
+  if (xml.nodeType === 1) {
+    // element node
+    // 处理子节点
+    if (xml.childNodes.length > 0) {
+      for (let i = 0; i < xml.childNodes.length; i++) {
+        const item = xml.childNodes[i]
+        const nodeName = item.nodeName.replace('wpml:', '')
+
+        // 检查是否是文本节点
+        if (item.nodeType === 3) {
+          // text node
+          // 处理文本节点的内容
+          if (item.nodeValue.trim() !== '') {
+            obj[nodeName] = item.nodeValue.trim()
+          }
+        } else if (item.nodeType === 1) {
+          // element node
+          // 递归调用处理子节点
+          if (obj[nodeName] === undefined) {
+            const nodeValue = deepParse(item)
+            if (nodeValue[nodeName] === undefined) {
+              obj[nodeName] = nodeValue
+            } else {
+              obj[nodeName] = nodeValue[nodeName]
+            }
+          } else {
+            if (!obj[nodeName].push) {
+              const old = obj[nodeName]
+              obj[nodeName] = []
+              obj[nodeName].push(old)
+            }
+            const nodeValue = deepParse(item)
+            if (nodeValue[nodeName] === undefined) {
+              obj[nodeName].push(nodeValue)
+            }
+          }
         }
-        xmlObj[childName].push(child.textContent)
-      } else {
-        const value = child.textContent?.split('\n').join('').split(' ').join('')
-        xmlObj[childName.replace('wpml:', '')] = value
       }
     }
+  } else if (xml.nodeType === 3) {
+    // text node
+    // 处理文本节点的内容
+    obj = xml.nodeValue.trim()
   }
-  return xmlObj
+  return obj
 }
-export const XMLToJSON = (xmlStr: string, tagName: string) => {
+
+/**
+ * @description: XML转JSON
+ * @param {string} xmlStr xml字符串
+ * @return {*} string
+ */
+export const XMLToJSON = (xmlStr: string) => {
   const parser = new DOMParser()
   const xmlDoc = parser.parseFromString(xmlStr, 'text/xml')
-  const xmlObj = deepParse(xmlDoc, tagName)
-  delete xmlObj.parsererror
-  return xmlObj
+  const xmlObj = deepParse(xmlDoc.documentElement)
+  if (Reflect.has(xmlObj, 'Document')) {
+    return xmlObj
+  } else {
+    return {
+      Document: xmlObj,
+    }
+  }
 }
 
 // json转xml
-export const JSONToXML = (JSONData = {}) => {
-  if (!JSONData) return ''
-  let res = ''
-  const JSONParse = (obj: { [x: string]: any }) => {
-    for (const key in obj) {
-      if (Array.isArray(obj[key])) {
-        obj[key].forEach((item: any, index: any) => {
-          let xmlTag = ''
-          if (noWmpl.includes(key)) {
-            xmlTag = `<${key} rowNum="${index}">${item}</${key}>`
+/**
+ * @description: JSON转XML
+ * @param {any} obj 要转换的对象
+ * @param {string} rootName xml根节点名称
+ * @return {*} string
+ */
+export const JSONToXML = (obj: any, rootName?: string | undefined, isEnd: boolean = false) => {
+  let xml = ''
+
+  const buildXml = (obj: string | any[], rootName: string = '') => {
+    let xml = ''
+    if (Array.isArray(obj)) {
+      obj.forEach((item) => {
+        const str = !noWmpl.includes(rootName) && isEnd ? 'wpml:' : ''
+        xml += `<${str}${rootName}>${buildXml(item)}</${str}${rootName}>`
+      })
+    } else if (typeof obj === 'object') {
+      Object.keys(obj).forEach((key) => {
+        if (key === '#text') {
+          xml += obj[key]
+        } else {
+          const str = !noWmpl.includes(key) && isEnd ? 'wpml:' : ''
+          if (key === 'Placemark') {
+            xml += `${buildXml(obj[key], key)}`
           } else {
-            xmlTag = `<wpml:${key} rowNum="${index}">${item}</wpml:${key}>`
+            xml += `<${str}${key}>${buildXml(obj[key], key)}</${str}${key}>`
           }
-          res += xmlTag
-        })
-      } else if (typeof obj[key] === 'object') {
-        res += (noWmpl.includes(key) ? `<${key}>` : `<wpml:${key}>`)
-        JSONParse(obj[key])
-        res += (noWmpl.includes(key) ? `</${key}>` : `</wpml:${key}>`)
-      } else {
-        res += (noWmpl.includes(key) ? `<${key}>${obj[key] || ''}</${key}>` : `<wpml:${key}>${obj[key] || ''}</wpml:${key}>`)
-      }
+        }
+      })
+    } else {
+      xml += obj
     }
+    return xml
   }
-  JSONParse(JSONData)
-  return res
+
+  const header = isEnd ? '<?xml version="1.0" encoding="UTF-8"?>' : ''
+  xml += `${header}
+  <kml xmlns="http://www.opengis.net/kml/2.2" xmlns:wpml="http://www.dji.com/wpmz/1.0.5">
+    <Document>
+      ${buildXml(obj, rootName)}
+    </Document>
+  </kml>`
+  return xml
 }

--
Gitblit v1.9.3