Filippo Bertilotti
2024-07-15 488dbe0a4f0d5be738a5ac010d19a94ce45f20a2
commit | author | age
d2a29b 1 function isValueText(obj) {
DC 2     const objName = obj.nodeName //obj.firstChild.nodeName
3     let objNodes = obj.childNodes //obj.firstChild.childNodes
4
5     let objKeys = Object.keys(objNodes);
6     return (objName === '#text') || ((objKeys.length !== 0) && (objNodes[objKeys[0]].nodeType === 3));
7 }
8
9 $.extend({
10     // converts xml documents and xml text to json object
11     json2xml: function (jsonObj, config) {
12         config = config || {};
13         initConfigDefaults();
14
15         return parseJSONObject(jsonObj);
16
17         function initConfigDefaults() {
18             if (config.escapeMode === undefined) {
19                 config.escapeMode = true;
20             }
21             config.attributePrefix = config.attributePrefix || "_";
22             config.arrayAccessForm = config.arrayAccessForm || "none";
23             config.emptyNodeForm = config.emptyNodeForm || "text";
24             if (config.enableToStringFunc === undefined) {
25                 config.enableToStringFunc = true;
26             }
27             config.arrayAccessFormPaths = config.arrayAccessFormPaths || [];
28             if (config.skipEmptyTextNodesForObj === undefined) {
29                 config.skipEmptyTextNodesForObj = true;
30             }
31             if (config.stripWhitespaces === undefined) {
32                 config.stripWhitespaces = true;
33             }
34             config.datetimeAccessFormPaths = config.datetimeAccessFormPaths || [];
35         }
36
37         function startTag(jsonObj, element, attrList, closed) {
38             var resultStr = "<" + ((jsonObj != null && jsonObj.__prefix != null) ? (jsonObj.__prefix + ":") : "") + element;
39             if (attrList != null) {
40                 for (var aidx = 0; aidx < attrList.length; aidx++) {
41                     var attrName = attrList[aidx];
42                     var attrVal = jsonObj[attrName];
43                     if (config.escapeMode)
44                         attrVal = escapeXmlChars(attrVal);
45                     resultStr += " " + attrName.substr(config.attributePrefix.length) + "='" + attrVal + "'";
46                 }
47             }
48             if (!closed)
49                 resultStr += ">";
50             else
51                 resultStr += "/>";
52             return resultStr;
53         }
54
55         function endTag(jsonObj, elementName) {
56             return "</" + (jsonObj.__prefix != null ? (jsonObj.__prefix + ":") : "") + elementName + ">";
57         }
58
59         function endsWith(str, suffix) {
60             return str.indexOf(suffix, str.length - suffix.length) !== -1;
61         }
62
63         function escapeXmlChars(str) {
64             if (typeof (str) == "string")
65                 return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g, '&#x2F;');
66             else
67                 return str;
68         }
69
70         function jsonXmlSpecialElem(jsonObj, jsonObjField) {
71             if ((config.arrayAccessForm == "property" && endsWith(jsonObjField.toString(), ("_asArray")))
72                 || jsonObjField.toString().indexOf(config.attributePrefix) == 0
73                 || jsonObjField.toString().indexOf("__") == 0
74                 || (jsonObj[jsonObjField] instanceof Function))
75                 return true;
76             else
77                 return false;
78         }
79
80         function jsonXmlElemCount(jsonObj) {
81             var elementsCnt = 0;
82             if (jsonObj instanceof Object) {
83                 for (var it in jsonObj) {
84                     if (jsonXmlSpecialElem(jsonObj, it))
85                         continue;
86                     elementsCnt++;
87                 }
88             }
89             return elementsCnt;
90         }
91
92         function parseJSONObject(jsonObj) {
93             var result = "";
94
95             var elementsCnt = jsonXmlElemCount(jsonObj);
96
97             if (elementsCnt > 0) {
98                 for (var it in jsonObj) {
99
100                     if (jsonXmlSpecialElem(jsonObj, it))
101                         continue;
102
103                     var subObj = jsonObj[it];
104
105                     var attrList = parseJSONAttributes(subObj)
106
107                     if (subObj == null) {
108                         result += startTag(subObj, it, attrList, true);
109                     } else if (subObj instanceof Object) {
110
111                         if (subObj instanceof Array) {
112                             result += parseJSONArray(subObj, it, attrList);
113                         } else if (subObj instanceof Date) {
114                             result += startTag(subObj, it, attrList, false);
115                             result += subObj.toISOString();
116                             result += endTag(subObj, it);
117                         } else {
118                             var subObjElementsCnt = jsonXmlElemCount(subObj);
119                             if (subObjElementsCnt > 0 || subObj.__text != null || subObj.__cdata != null) {
120                                 result += startTag(subObj, it, attrList, false);
121                                 result += parseJSONObject(subObj);
122                                 result += endTag(subObj, it);
123                             } else {
124                                 result += startTag(subObj, it, attrList, true);
125                             }
126                         }
127                     } else {
128                         result += startTag(subObj, it, attrList, false);
129                         result += parseJSONTextObject(subObj);
130                         result += endTag(subObj, it);
131                     }
132                 }
133             }
134             result += parseJSONTextObject(jsonObj);
135
136             return result;
137         }
138
139         function parseJSONAttributes(jsonObj) {
140             var attrList = [];
141             if (jsonObj instanceof Object) {
142                 for (var ait in jsonObj) {
143                     if (ait.toString().indexOf("__") == -1 && ait.toString().indexOf(config.attributePrefix) == 0) {
144                         attrList.push(ait);
145                     }
146                 }
147             }
148             return attrList;
149         }
150
151         function parseJSONTextAttrs(jsonTxtObj) {
152             var result = "";
153
154             if (jsonTxtObj.__cdata != null) {
155                 result += "<![CDATA[" + jsonTxtObj.__cdata + "]]>";
156             }
157
158             if (jsonTxtObj.__text != null) {
159                 if (config.escapeMode)
160                     result += escapeXmlChars(jsonTxtObj.__text);
161                 else
162                     result += jsonTxtObj.__text;
163             }
164             return result;
165         }
166
167         function parseJSONTextObject(jsonTxtObj) {
168             var result = "";
169
170             if (jsonTxtObj instanceof Object) {
171                 result += parseJSONTextAttrs(jsonTxtObj);
172             } else if (jsonTxtObj != null) {
173                 if (config.escapeMode)
174                     result += escapeXmlChars(jsonTxtObj);
175                 else
176                     result += jsonTxtObj;
177             }
178
179             return result;
180         }
181
182         function parseJSONArray(jsonArrRoot, jsonArrObj, attrList) {
183             var result = "";
184             if (jsonArrRoot.length == 0) {
185                 result += startTag(jsonArrRoot, jsonArrObj, attrList, true);
186             } else {
187                 for (var arIdx = 0; arIdx < jsonArrRoot.length; arIdx++) {
188                     result += startTag(jsonArrRoot[arIdx], jsonArrObj, parseJSONAttributes(jsonArrRoot[arIdx]), false);
189                     result += parseJSONObject(jsonArrRoot[arIdx]);
190                     result += endTag(jsonArrRoot[arIdx], jsonArrObj);
191                 }
192             }
193             return result;
194         }
195
196     },
197     xml2json: function parseXmlToJson(xml) {
198         const json = {};
199         for (const res of xml.matchAll(/(?:<(\w*)(?:\s[^>]*)*>)((?:(?!<\1).)*)(?:<\/\1>)|<(\w*)(?:\s*)*\/>/gm)) {
200             const key = res[1] || res[3];
201             const value = res[2] && parseXmlToJson(res[2]);
202             json[key] = ((value && Object.keys(value).length) ? value : res[2]) || null;
203
204         }
205         return json;
206     },
207     isXmlValid: function (xml) {
208         try {
209             const jsonObj = this.xml2json(xml)
210             const jsonStr = JSON.stringify(jsonObj)
211             const newJsonObj = JSON.parse(jsonStr)
212             if (jsonObj && jsonStr && newJsonObj) {
213                 return true;
214             }
215         } catch (err) {
216             console.log("errore nella validazione del xml: " + err)
217             return err
218         }
219         return false
220     }
221 });