吉安感知网项目-前端
shuishen
5 days ago 6e88705bd5b443a259b24c17c8a299765d059d96
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import axios from 'axios'
import JsZip from 'jszip'
 
const noWmpl = ['Folder', 'Placemark', 'Point', 'coordinates']
 
/**
 * @description: 读取kmz文件解析出kml文件
 * @param {string} filePath 文件地址
 * @return {*}
 */
export const analyzeKmzFile = filePath => {
    return (
        axios({
            url: filePath,
            method: 'get',
            responseType: 'arraybuffer',
            authorization: false,
        })
            // .get(filePath, { responseType: 'arraybuffer' },)
            .then(fileRes => fileRes.data)
            .then(kmzData => JsZip.loadAsync(kmzData)) // 解压kmz文件
            .then(zipFile => {
                const files = {}
                Object.keys(zipFile.files).forEach(key => {
                    files[key] = zipFile.files[key].async('text')
                })
                return {
                    zip: zipFile,
                    fileInfoObj: files,
                }
            })
    )
}
 
export const getKmlParams = (source, isWpml, params) => {
    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 => {
    let paramGroup = ''
    Object.keys(settingParmas).forEach(key => {
        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
}
 
/**
 * @description: JSON转XML
 * @param {any} obj 要转换的对象
 * @param {string} rootName xml根节点名称
 * @return {*} string
 */
export const JSONToXML = (obj, rootName, isEnd) => {
    let xml = ''
 
    const buildXml = (obj, rootName) => {
        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 if (key === 'action') {
                        if (Array.isArray(obj[key])) {
                            xml += `${buildXml(obj[key], key)}`
                        } else {
                            xml += `<${str}${key}>${buildXml(obj[key], key)}</${str}${key}>`
                        }
                    } else {
                        xml += `<${str}${key}>${buildXml(obj[key], key)}</${str}${key}>`
                    }
                }
            })
        } else {
            xml += obj
        }
        return xml
    }
 
    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
}
 
export const getTagNameFromXml = xmlString => {
    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 = xml => {
    let obj = {}
    // 如果是文档节点,遍历其子节点
    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)
                        }
                    }
                }
            }
        }
    } else if (xml.nodeType === 3) {
        // text node
        // 处理文本节点的内容
        obj = xml.nodeValue.trim()
    }
    return obj
}
 
/**
 * @description: XML转JSON
 * @param {string} xmlStr xml字符串
 * @return {*} string
 */
export const XMLToJSON = xmlStr => {
    const parser = new DOMParser()
    const xmlDoc = parser.parseFromString(xmlStr, 'text/xml')
    const xmlObj = deepParse(xmlDoc.documentElement)
    if (Reflect.has(xmlObj, 'Document')) {
        return xmlObj
    } else {
        return {
            Document: xmlObj,
        }
    }
}
 
 
/**
 * 递归处理对象,移除 #text 键并返回其值,同时处理数值字符串到数字的转换
 * @param {any} obj - 需要处理的对象或值
 * @returns {any} 处理后的对象或值
 */
export function removeTextKey(obj) {
    if (typeof obj !== 'object' || obj === null) {
        // 如果是数值字符串,转换为数值
        if (typeof obj === 'string' && /^-?\d+(\.\d+)?$/.test(obj)) {
            return Number(obj);
        }
        return obj;
    }
 
    if (Array.isArray(obj)) {
        // 递归处理数组中的每个元素
        return obj.map(item => removeTextKey(item));
    }
 
    if (Object.prototype.hasOwnProperty.call(obj, '#text')) {
        // 如果存在 #text 属性,返回其值(如果是数值字符串则转换为数字)
        const textValue = obj['#text'];
        return typeof textValue === 'string' && /^-?\d+(\.\d+)?$/.test(textValue) ? Number(textValue) : textValue;
    }
 
    // 递归处理对象属性
    const newObj = {};
    for (const key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            // 如果属性值是空对象,则设为空字符串;否则递归处理
            newObj[key] = Object.keys(obj[key]).length === 0 ? '' : removeTextKey(obj[key]);
        }
    }
    return newObj;
}