davide.cucurnia@vola.it
2024-02-01 555a537e2e5d9220e3777c30b185606823c817f2
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
function isValueText(obj) {
    const objName = obj.nodeName //obj.firstChild.nodeName
    let objNodes = obj.childNodes //obj.firstChild.childNodes
 
    let objKeys = Object.keys(objNodes);
    return (objName === '#text') || ((objKeys.length !== 0) && (objNodes[objKeys[0]].nodeType === 3));
}
 
$.extend({
    // converts xml documents and xml text to json object
    json2xml: function (jsonObj, config) {
        config = config || {};
        initConfigDefaults();
 
        return parseJSONObject(jsonObj);
 
        function initConfigDefaults() {
            if (config.escapeMode === undefined) {
                config.escapeMode = true;
            }
            config.attributePrefix = config.attributePrefix || "_";
            config.arrayAccessForm = config.arrayAccessForm || "none";
            config.emptyNodeForm = config.emptyNodeForm || "text";
            if (config.enableToStringFunc === undefined) {
                config.enableToStringFunc = true;
            }
            config.arrayAccessFormPaths = config.arrayAccessFormPaths || [];
            if (config.skipEmptyTextNodesForObj === undefined) {
                config.skipEmptyTextNodesForObj = true;
            }
            if (config.stripWhitespaces === undefined) {
                config.stripWhitespaces = true;
            }
            config.datetimeAccessFormPaths = config.datetimeAccessFormPaths || [];
        }
 
        function startTag(jsonObj, element, attrList, closed) {
            var resultStr = "<" + ((jsonObj != null && jsonObj.__prefix != null) ? (jsonObj.__prefix + ":") : "") + element;
            if (attrList != null) {
                for (var aidx = 0; aidx < attrList.length; aidx++) {
                    var attrName = attrList[aidx];
                    var attrVal = jsonObj[attrName];
                    if (config.escapeMode)
                        attrVal = escapeXmlChars(attrVal);
                    resultStr += " " + attrName.substr(config.attributePrefix.length) + "='" + attrVal + "'";
                }
            }
            if (!closed)
                resultStr += ">";
            else
                resultStr += "/>";
            return resultStr;
        }
 
        function endTag(jsonObj, elementName) {
            return "</" + (jsonObj.__prefix != null ? (jsonObj.__prefix + ":") : "") + elementName + ">";
        }
 
        function endsWith(str, suffix) {
            return str.indexOf(suffix, str.length - suffix.length) !== -1;
        }
 
        function escapeXmlChars(str) {
            if (typeof (str) == "string")
                return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g, '&#x2F;');
            else
                return str;
        }
 
        function jsonXmlSpecialElem(jsonObj, jsonObjField) {
            if ((config.arrayAccessForm == "property" && endsWith(jsonObjField.toString(), ("_asArray")))
                || jsonObjField.toString().indexOf(config.attributePrefix) == 0
                || jsonObjField.toString().indexOf("__") == 0
                || (jsonObj[jsonObjField] instanceof Function))
                return true;
            else
                return false;
        }
 
        function jsonXmlElemCount(jsonObj) {
            var elementsCnt = 0;
            if (jsonObj instanceof Object) {
                for (var it in jsonObj) {
                    if (jsonXmlSpecialElem(jsonObj, it))
                        continue;
                    elementsCnt++;
                }
            }
            return elementsCnt;
        }
 
        function parseJSONObject(jsonObj) {
            var result = "";
 
            var elementsCnt = jsonXmlElemCount(jsonObj);
 
            if (elementsCnt > 0) {
                for (var it in jsonObj) {
 
                    if (jsonXmlSpecialElem(jsonObj, it))
                        continue;
 
                    var subObj = jsonObj[it];
 
                    var attrList = parseJSONAttributes(subObj)
 
                    if (subObj == null) {
                        result += startTag(subObj, it, attrList, true);
                    } else if (subObj instanceof Object) {
 
                        if (subObj instanceof Array) {
                            result += parseJSONArray(subObj, it, attrList);
                        } else if (subObj instanceof Date) {
                            result += startTag(subObj, it, attrList, false);
                            result += subObj.toISOString();
                            result += endTag(subObj, it);
                        } else {
                            var subObjElementsCnt = jsonXmlElemCount(subObj);
                            if (subObjElementsCnt > 0 || subObj.__text != null || subObj.__cdata != null) {
                                result += startTag(subObj, it, attrList, false);
                                result += parseJSONObject(subObj);
                                result += endTag(subObj, it);
                            } else {
                                result += startTag(subObj, it, attrList, true);
                            }
                        }
                    } else {
                        result += startTag(subObj, it, attrList, false);
                        result += parseJSONTextObject(subObj);
                        result += endTag(subObj, it);
                    }
                }
            }
            result += parseJSONTextObject(jsonObj);
 
            return result;
        }
 
        function parseJSONAttributes(jsonObj) {
            var attrList = [];
            if (jsonObj instanceof Object) {
                for (var ait in jsonObj) {
                    if (ait.toString().indexOf("__") == -1 && ait.toString().indexOf(config.attributePrefix) == 0) {
                        attrList.push(ait);
                    }
                }
            }
            return attrList;
        }
 
        function parseJSONTextAttrs(jsonTxtObj) {
            var result = "";
 
            if (jsonTxtObj.__cdata != null) {
                result += "<![CDATA[" + jsonTxtObj.__cdata + "]]>";
            }
 
            if (jsonTxtObj.__text != null) {
                if (config.escapeMode)
                    result += escapeXmlChars(jsonTxtObj.__text);
                else
                    result += jsonTxtObj.__text;
            }
            return result;
        }
 
        function parseJSONTextObject(jsonTxtObj) {
            var result = "";
 
            if (jsonTxtObj instanceof Object) {
                result += parseJSONTextAttrs(jsonTxtObj);
            } else if (jsonTxtObj != null) {
                if (config.escapeMode)
                    result += escapeXmlChars(jsonTxtObj);
                else
                    result += jsonTxtObj;
            }
 
            return result;
        }
 
        function parseJSONArray(jsonArrRoot, jsonArrObj, attrList) {
            var result = "";
            if (jsonArrRoot.length == 0) {
                result += startTag(jsonArrRoot, jsonArrObj, attrList, true);
            } else {
                for (var arIdx = 0; arIdx < jsonArrRoot.length; arIdx++) {
                    result += startTag(jsonArrRoot[arIdx], jsonArrObj, parseJSONAttributes(jsonArrRoot[arIdx]), false);
                    result += parseJSONObject(jsonArrRoot[arIdx]);
                    result += endTag(jsonArrRoot[arIdx], jsonArrObj);
                }
            }
            return result;
        }
 
    },
    xml2json: function parseXmlToJson(xml) {
        const json = {};
        for (const res of xml.matchAll(/(?:<(\w*)(?:\s[^>]*)*>)((?:(?!<\1).)*)(?:<\/\1>)|<(\w*)(?:\s*)*\/>/gm)) {
            const key = res[1] || res[3];
            const value = res[2] && parseXmlToJson(res[2]);
            json[key] = ((value && Object.keys(value).length) ? value : res[2]) || null;
 
        }
        return json;
    },
    isXmlValid: function (xml) {
        try {
            const jsonObj = this.xml2json(xml)
            const jsonStr = JSON.stringify(jsonObj)
            const newJsonObj = JSON.parse(jsonStr)
            if (jsonObj && jsonStr && newJsonObj) {
                return true;
            }
        } catch (err) {
            console.log("errore nella validazione del xml: " + err)
            return err
        }
        return false
    }
});