GuLiMmo
2024-03-12 55fcb97a3d487f54353564f1e402e4d4b61feee9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
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']
 
/**
 * @description: 读取kmz文件解析出kml文件
 * @param {string} filePath 文件地址
 * @return {*}
 */
export const analyzeKmzFile = (filePath: string) => {
  return axios
    .get(filePath, { responseType: 'arraybuffer' })
    .then((fileRes) => fileRes.data)
    .then((kmzData) => JsZip.loadAsync(kmzData)) // 解压kmz文件
    .then((zipFile) => {
      const files: { [key: string]: Promise<string> } = {}
      Object.keys(zipFile.files).forEach((key: string) => {
        files[key] = zipFile.files[key].async('text')
      })
      return {
        zip: zipFile,
        fileInfoObj: files,
      }
    })
}
 
export const getKmlParams = (
  source: string,
  isWpml: boolean,
  params: { name: string | undefined; findRegx: string; mode?: string },
) => {
  let regx = null
  if (isWpml) {
    if (params.mode) {
      regx = new RegExp(`<wpml:${params.name}>${params.findRegx}<\\/wpml:${params.name}>`, params.mode)
    } else {
      regx = new RegExp(`<wpml:${params.name}>${params.findRegx}<\\/wpml:${params.name}>`)
    }
  } else {
    if (params.mode) {
      regx = new RegExp(`<${params.name}>${params.findRegx}<\\/${params.name}>`, params.mode)
    } else {
      regx = new RegExp(`<${params.name}>${params.findRegx}<\\/${params.name}>`)
    }
  }
  return source?.match(regx)
}
 
export const generateKmlFormat = (settingParmas: any) => {
  let paramGroup = ''
  Object.keys(settingParmas).forEach((key: string) => {
    if (Object.prototype.toString.call(settingParmas[key]) === '[object Object]') {
      let parmaStr = ''
      Object.keys(settingParmas[key]).forEach((v) => {
        const xml = noWmpl.includes(key)
          ? `<${v}>${settingParmas[key][v]}</${v}>`
          : `<wpml:${v}>${settingParmas[key][v]}</wpml:${v}>`
        parmaStr += xml
      })
      const xml = noWmpl.includes(key) ? `<${key}>${parmaStr}</${key}>` : `<wpml:${key}>${parmaStr}</wpml:${key}>`
      paramGroup += xml
    } else {
      const xml = noWmpl.includes(key)
        ? `<${key}>${settingParmas[key]}</${key}>`
        : `<wpml:${key}>${settingParmas[key]}</wpml:${key}>`
      paramGroup += xml
    }
  })
  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')
  const element = xmlDoc.documentElement
  if (element && element.tagName) {
    return element.tagName // 返回的是类似 "WPML:USEGLOBALHEADINGPARAM" 的全大写形式
  }
  return null
}
 
// 将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]]
        }
        xmlObj[childName].push(child.textContent)
      } else {
        const value = child.textContent?.split('\n').join('').split(' ').join('')
        xmlObj[childName.replace('wpml:', '')] = value
      }
    }
  }
  return xmlObj
}
export const XMLToJSON = (xmlStr: string, tagName: string) => {
  const parser = new DOMParser()
  const xmlDoc = parser.parseFromString(xmlStr, 'text/xml')
  const xmlObj = deepParse(xmlDoc, tagName)
  delete xmlObj.parsererror
  return 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}>`
          } else {
            xmlTag = `<wpml:${key} rowNum="${index}">${item}</wpml:${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}>`)
      }
    }
  }
  JSONParse(JSONData)
  return res
}