-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxml_parser.js
More file actions
301 lines (289 loc) · 7.7 KB
/
xml_parser.js
File metadata and controls
301 lines (289 loc) · 7.7 KB
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
293
294
295
296
297
298
299
300
301
var util = require("util"),
extend = require("extend");
/**
* special tag handling for html dom parser
*/
var specialTags = {
"#text" : true,
"#comment" : true
};
var startRegex = /<([a-zA-Z]\S*?)((\s+.*?=".*?"\s*)*)(>|\/>)/;
var commentRegex = /<!--([\s\S]*?)-->/g;
/**
* create the xml parser class to issolate the option for each parsing
*/
var defaultOptions = {
html:false,
wsdl: false,
xml: true,
swagger: false,
excludeRoot: false
}
var XmlParser = function(options){
this.options = extend({},defaultOptions,options);
this.commentCollection = {};
};
XmlParser.prototype = {
parse: function(xml, obj) {
var obj = obj || {};
//get start tag
if (!xml || typeof(xml)!="string")
return obj;
xml = extractComment(this.commentCollection, xml, this.options.html);
//handle textNode for html dom parser
var tagName, content, attr = null;
var index = xml.indexOf("<");
if (index != 0 && this.options.html) {
tagName = "#text";
if (index == -1) {
content = xml;
xml = "";
} else {
content = xml.substr(0, index);//.replace(/[\s\r\n]+$/,"");
xml = xml.substr(index);
}
} else {
var match = xml.match(startRegex);
if (!match)
return obj;
tagName = match[1];
var attrStr = match[2];
attr = getAttr(attrStr);
var isEmptyTag = match[match.length - 1] == "/>";
if(isEmptyTag){
content = "";
xml = xml.replace(match[0],"");
}
else{
var nRegexStr = "<" + tagName + "[^>]*>([\\s\\S]*?)<\\/" + tagName + ">";
var nRegex = new RegExp(nRegexStr);
var nMatch = xml.match(nRegex);
if (!nMatch)
return obj;
content = nMatch[1];
xml = xml.replace(nRegex, "");
}
}
if (this.options.xml) {
obj = this.addXmlElement(obj, attr, content, tagName);
} else if (this.options.html) {
//dom parser every tag = object.
//supported properties: nodeName, textNode, innerHTML, childNodes, attributes
this.addHtmlElement(obj, attr, content, tagName);
}
return this.parse(xml, obj);
},
/**
* need to return the obj, since obj may converted from object to array which point to different address
*/
addXmlElement: function(obj, attr, content, tagName) {
//handle CDATA
//console.log("addExmlElement tag: %s, content: %s", tagName, content);
var m = content.match(/^\s*<!\[CDATA\[([\s\S]*?)\]\]>\s*$/);
if(m){
console.log("cdata matched");
console.log(m);
addXmlContent(obj,tagName,m[1]);
return obj;
}
//handle leaf node
if(content.indexOf("<") == -1){
var val = getValue(content, attr, this.options);
addXmlContent(obj,tagName,val);
return obj;
}
//handle for child node
var val = this.parse(content);
if (obj[tagName]) {
var v = obj[tagName];
var tmp = {};
tmp[tagName] = v;
obj = [tmp];
}
if (util.isArray(obj)) {
var tmp = {};
tmp[tagName] = val;
obj.push(tmp);
}
else if(attr && attr.type=="array"){
obj[tagName] = [val];
}
else {
obj[tagName] = val;
}
return obj;
},
addHtmlElement: function(obj, attr, content, tagName) {
if (util.isArray(obj)) {
if (tagName == "#text") {
//console.log(util.format("this.commentCollection: %j", this.commentCollection));
processTextNode(this.commentCollection, content, obj);
} else {
var tmp = {};
tmp.nodeName = tagName.toUpperCase();
tmp.innerHTML = content;
tmp.childNodes = obj.childNodes || [];
addAttr(tmp, attr);
this.parse(content, tmp.childNodes);
obj.push(tmp);
}
} else {
obj.nodeName = (tagName in specialTags) ? tagName : tagName.toUpperCase();
obj.innerHTML = content;
obj.childNodes = obj.childNodes || [];
addAttr(obj, attr);
if (content.indexOf("<") == -1) {
createTextNode(content, obj.childNodes);
} else {
this.parse(content, obj.childNodes);
}
}
}
};
//================= share private function for all object ======================
function addXmlContent(obj,tagName,val){
//check if property already added, then convert it to array.
if (obj[tagName] && !util.isArray(obj[tagName])) {
var v = obj[tagName];
obj[tagName] = [v];
}
if (util.isArray(obj[tagName])) {
obj[tagName].push(val);
} else {
obj[tagName] = val;
}
}
/**
* xml: remove comment block
* html: replace comment with a unique string which will be process later
*/
function extractComment(commentCollection, xml, isHtml) {
if (isHtml) {
xml = xml.replace(commentRegex, function(m0, m1) {
var id = "#comment" + Math.random().toString(36).substr(2, 10);
commentCollection[id] = {
nodeName : "#comment",
textContent : m1,
data : m1
};
return id;
});
} else {
//handle comment: remove it from the xml, for html convert it to comment tag, and trim start and end of ptags
xml = xml.replace(commentRegex, "");
xml = xml.replace(/^[^<]+/, "").replace(/[^>]+$/, "");
}
return xml;
}
function processTextNode(commentCollection, txt, arr) {
txt = txt.replace(/([\s\S]*?)(#comment\w{10})/g, function(m0, m1, m2) {
//console.log("adding comment node m1: %s, m2: %s", m1, m2);
if (m1) {
arr.push({
nodeName : "#text",
textContent : m1,
data : txt
});
}
arr.push(commentCollection[m2]);
return "";
});
if (txt) {
arr.push({
nodeName : "#text",
textContent : txt,
data : txt
});
}
}
//simple clone
function clone(obj) {
var o = {};
for (var i in obj) {
if (typeof (obj[i]) == "object") {
o[i] = clone(obj[i]);
} else {
o[i] = obj[i];
}
}
return o;
}
function addAttr(obj, attr) {
if (!attr || !obj || typeof (obj) != "object")
return;
for ( var i in attr) {
obj[i] = attr[i];
}
}
function getAttr(str) {
if (!str)
return null;
var attr = {};
var match = str.match(/(.+?=".+?")/g);
for (var i = 0; i < match.length; i++) {
var s = match[i].replace(/^\s*/, "").replace(/\s*?/, "");
var m = s.match(/(.+)="(.+)"/);
if (!m)
throw "attribute is not well formatted" + attrStr;
attr[m[1]] = m[2];
}
return attr;
}
/**
* helper function to get attribute value for WSDL
* @param content
* @param attr
* @param options
* @returns
*/
function getValue(content, attr, options) {
content = decodeXml(content);
content = decodeURIComponent(content);
if (!options.wsdl && !options.swagger){
console.log("no parsing value")
return content;
}
if (!attr){
console.log("attr not defined");
return content;
}
switch (attr.type) {
case "integer":
return parseInt(content);
case "float":
case "number":
return parseFloat(content);
case "boolean":
return content.toLowerCase() == "true";
case "array":
return [content];
default:
return content;
}
}
function encodeXml(str) {
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function decodeXml(str) {
return str.replace(/'/g, "'")
.replace(/"/g, '"')
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/&/g, '&');
}
///=========== Expose node module function===================
var parser = function(xml,options){
var xmlParser = new XmlParser(options);
var dom = xmlParser.parse(xml);
if(!xmlParser.options.excludeRoot){
return dom;
}
for(var i in dom){
return dom[i];
}
};
module.exports = parser;