forked from tyrasd/jxon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
292 lines (261 loc) · 11.6 KB
/
index.js
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/*
* JXON framework - Copyleft 2011 by Mozilla Developer Network
*
* Revision #1 - September 5, 2014
*
* https://developer.mozilla.org/en-US/docs/JXON
*
* This framework is released under the GNU Public License, version 3 or later.
* http://www.gnu.org/licenses/gpl-3.0-standalone.html
*
* small modifications performed by the iD project:
* https://github.com/openstreetmap/iD/commits/18aa33ba97b52cacf454e95c65d154000e052a1f/js/lib/jxon.js
*
* small modifications performed by user @bugreport0
* https://github.com/tyrasd/JXON/pull/2/commits
*
* some additions and modifications by user @igord
* https://github.com/tyrasd/JXON/pull/5/commits
*
* adapted for nodejs and npm by Martin Raifer <[email protected]>
*/
/*
* Modifications:
* - added config method that excepts objects with props:
* - valueKey (default: keyValue)
* - attrKey (default: keyAttributes)
* - attrPrefix (default: @)
* - lowerCaseTags (default: true)
* - trueIsEmpty (default: true)
* - autoDate (default: true)
* - turning tag and attributes to lower case is optional
* - optional turning boolean true to empty tag
* - auto Date parsing is optional
* - added parseXml method
*
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory(window));
} else if (typeof exports === 'object') {
if (typeof window === 'object' && window.DOMImplementation) {
// Browserify. hardcode usage of browser's own XMLDom implementation
// see https://github.com/tyrasd/jxon/issues/18
module.exports = factory(window);
} else {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require('xmldom'));
}
} else {
// Browser globals (root is window)
root.JXON = factory(window);
}
}(this, function (xmlDom) {
return new (function () {
var
sValProp = "keyValue",
sAttrProp = "keyAttributes",
sAttrsPref = "@",
sLowCase = true,
sEmptyTrue = true,
sAutoDate = true,
sIgnorePrefixed = false,
parserErrorHandler,
DOMParser,
sParseValues = true, /* you can customize these values */
aCache = [], rIsNull = /^\s*$/, rIsBool = /^(?:true|false)$/i;
function parseText (sValue) {
if (!sParseValues) return sValue;
if (rIsNull.test(sValue)) { return null; }
if (rIsBool.test(sValue)) { return sValue.toLowerCase() === "true"; }
if (isFinite(sValue)) { return parseFloat(sValue); }
if (sAutoDate && isFinite(Date.parse(sValue))) { return new Date(sValue); }
return sValue;
}
function EmptyTree () { }
EmptyTree.prototype.toString = function () { return "null"; };
EmptyTree.prototype.valueOf = function () { return null; };
function objectify (vValue) {
return vValue === null ? new EmptyTree() : vValue instanceof Object ? vValue : new vValue.constructor(vValue);
}
function createObjTree (oParentNode, nVerb, bFreeze, bNesteAttr) {
var
nLevelStart = aCache.length, bChildren = oParentNode.hasChildNodes(),
bAttributes = oParentNode.nodeType === oParentNode.ELEMENT_NODE && oParentNode.hasAttributes(), bHighVerb = Boolean(nVerb & 2);
var
sProp, vContent, nLength = 0, sCollectedTxt = "",
vResult = bHighVerb ? {} : /* put here the default value for empty nodes: */ (sEmptyTrue ? true : '');
if (bChildren) {
for (var oNode, nItem = 0; nItem < oParentNode.childNodes.length; nItem++) {
oNode = oParentNode.childNodes.item(nItem);
if (oNode.nodeType === 4) { sCollectedTxt += oNode.nodeValue; } /* nodeType is "CDATASection" (4) */
else if (oNode.nodeType === 3) { sCollectedTxt += oNode.nodeValue.trim(); } /* nodeType is "Text" (3) */
else if (oNode.nodeType === 1 && !(sIgnorePrefixed && oNode.prefix)) { aCache.push(oNode); } /* nodeType is "Element" (1) */
}
}
var nLevelEnd = aCache.length, vBuiltVal = parseText(sCollectedTxt);
if (!bHighVerb && (bChildren || bAttributes)) { vResult = nVerb === 0 ? objectify(vBuiltVal) : {}; }
for (var nElId = nLevelStart; nElId < nLevelEnd; nElId++) {
sProp = aCache[nElId].nodeName;
if (sLowCase) sProp = sProp.toLowerCase();
vContent = createObjTree(aCache[nElId], nVerb, bFreeze, bNesteAttr);
if (vResult.hasOwnProperty(sProp)) {
if (vResult[sProp].constructor !== Array) { vResult[sProp] = [vResult[sProp]]; }
vResult[sProp].push(vContent);
} else {
vResult[sProp] = vContent;
nLength++;
}
}
if (bAttributes) {
var
nAttrLen = oParentNode.attributes.length,
sAPrefix = bNesteAttr ? "" : sAttrsPref, oAttrParent = bNesteAttr ? {} : vResult;
for (var oAttrib, oAttribName, nAttrib = 0; nAttrib < nAttrLen; nLength++, nAttrib++) {
oAttrib = oParentNode.attributes.item(nAttrib);
oAttribName = oAttrib.name;
if (sLowCase) oAttribName = oAttribName.toLowerCase();
oAttrParent[sAPrefix + oAttribName] = parseText(oAttrib.value.trim());
}
if (bNesteAttr) {
if (bFreeze) { Object.freeze(oAttrParent); }
vResult[sAttrProp] = oAttrParent;
nLength -= nAttrLen - 1;
}
}
if (nVerb === 3 || (nVerb === 2 || nVerb === 1 && nLength > 0) && sCollectedTxt) {
vResult[sValProp] = vBuiltVal;
} else if (!bHighVerb && nLength === 0 && sCollectedTxt) {
vResult = vBuiltVal;
}
if (bFreeze && (bHighVerb || nLength > 0)) { Object.freeze(vResult); }
aCache.length = nLevelStart;
return vResult;
}
function loadObjTree (oXMLDoc, oParentEl, oParentObj) {
var vValue, oChild;
if (oParentObj.constructor === String || oParentObj.constructor === Number || oParentObj.constructor === Boolean) {
oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toString())); /* verbosity level is 0 or 1 */
if (oParentObj === oParentObj.valueOf()) { return; }
} else if (oParentObj.constructor === Date) {
oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toGMTString()));
}
for (var sName in oParentObj) {
vValue = oParentObj[sName];
if (vValue === null) vValue = {};
if (isFinite(sName) || vValue instanceof Function) { continue; } /* verbosity level is 0 */
// when it is _
if (sName === sValProp) {
if (vValue !== null && vValue !== true) { oParentEl.appendChild(oXMLDoc.createTextNode(vValue.constructor === Date ? vValue.toGMTString() : String(vValue))); }
} else if (sName === sAttrProp) { /* verbosity level is 3 */
for (var sAttrib in vValue) { oParentEl.setAttribute(sAttrib, vValue[sAttrib]); }
} else if (sName === sAttrsPref+'xmlns') {
// do nothing: special handling of xml namespaces is done via createElementNS()
} else if (sName.charAt(0) === sAttrsPref) {
oParentEl.setAttribute(sName.slice(1), vValue);
} else if (vValue.constructor === Array) {
for (var nItem = 0; nItem < vValue.length; nItem++) {
oChild = oXMLDoc.createElementNS(vValue[nItem][sAttrsPref+'xmlns'] || oParentEl.namespaceURI, sName);
loadObjTree(oXMLDoc, oChild, vValue[nItem]);
oParentEl.appendChild(oChild);
}
} else {
oChild = oXMLDoc.createElementNS((vValue || {})[sAttrsPref+'xmlns'] || oParentEl.namespaceURI, sName);
if (vValue instanceof Object) {
loadObjTree(oXMLDoc, oChild, vValue);
} else if (vValue !== null && vValue !== true) {
oChild.appendChild(oXMLDoc.createTextNode(vValue.toString()));
} else if (!sEmptyTrue && vValue === true) {
oChild.appendChild(oXMLDoc.createTextNode(vValue.toString()));
}
oParentEl.appendChild(oChild);
}
}
}
this.xmlToJs = this.build = function (oXMLParent, nVerbosity /* optional */, bFreeze /* optional */, bNesteAttributes /* optional */) {
var _nVerb = arguments.length > 1 && typeof nVerbosity === "number" ? nVerbosity & 3 : /* put here the default verbosity level: */ 1;
return createObjTree(oXMLParent, _nVerb, bFreeze || false, arguments.length > 3 ? bNesteAttributes : _nVerb === 3);
};
this.jsToXml = this.unbuild = function (oObjTree, sNamespaceURI /* optional */, sQualifiedName /* optional */, oDocumentType /* optional */) {
var documentImplementation = xmlDom.document && xmlDom.document.implementation || new xmlDom.DOMImplementation();
var oNewDoc = documentImplementation.createDocument(sNamespaceURI || null, sQualifiedName || "", oDocumentType || null);
loadObjTree(oNewDoc, oNewDoc.documentElement || oNewDoc, oObjTree);
return oNewDoc;
};
this.config = function(o) {
if (typeof o === 'undefined') {
return {
valueKey: sValProp,
attrKey: sAttrProp,
attrPrefix: sAttrsPref,
lowerCaseTags: sLowCase,
trueIsEmpty: sEmptyTrue,
autoDate: sAutoDate,
ignorePrefixNodes: sIgnorePrefixed,
parseValues: sParseValues,
parserErrorHandler: parserErrorHandler
};
}
for (var k in o) {
switch(k) {
case 'valueKey':
sValProp = o.valueKey;
break;
case 'attrKey':
sAttrProp = o.attrKey;
break;
case 'attrPrefix':
sAttrsPref = o.attrPrefix;
break;
case 'lowerCaseTags':
sLowCase = o.lowerCaseTags;
break;
case 'trueIsEmpty':
sEmptyTrue = o.trueIsEmpty;
break;
case 'autoDate':
sAutoDate = o.autoDate;
break;
case 'ignorePrefixedNodes':
sIgnorePrefixed = o.ignorePrefixedNodes;
break;
case 'parseValues':
sParseValues = o.parseValues;
break;
case 'parserErrorHandler':
parserErrorHandler = o.parserErrorHandler;
DOMParser = new xmlDom.DOMParser({
errorHandler: parserErrorHandler,
locator: {}
});
break;
default:
break;
}
}
};
this.stringToXml = function(xmlStr) {
if (!DOMParser) DOMParser = new xmlDom.DOMParser();
return DOMParser.parseFromString(xmlStr, 'application/xml');
};
this.xmlToString = function (xmlObj) {
if (typeof xmlObj.xml !== "undefined") {
return xmlObj.xml;
} else {
return (new xmlDom.XMLSerializer()).serializeToString(xmlObj);
}
};
this.stringToJs = function(str) {
var xmlObj = this.stringToXml(str);
return this.xmlToJs(xmlObj);
};
this.jsToString = this.stringify = function(oObjTree, sNamespaceURI /* optional */, sQualifiedName /* optional */, oDocumentType /* optional */) {
return this.xmlToString(
this.jsToXml(oObjTree, sNamespaceURI, sQualifiedName, oDocumentType)
);
};
})();
}));