/
serialize.js
81 lines (69 loc) · 1.73 KB
/
serialize.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
var XMLWriter = require('xml-writer'),
xml = require('./xml'),
NodeSet = xml.NodeSet,
Tag = xml.Tag,
XML_TYPE = xml.XML_TYPE;
/**
* @param {XMLWriter} xw
* @param {Comment|CData|String} node
*/
function writeXMLAtomicType(xw, node) {
var type = xml.getXMLType(node);
switch (type) {
case XML_TYPE.COMMENT:
xw.writeComment(node.toString());
break;
case XML_TYPE.CDATA:
xw.writeCData(node.toString());
break;
case XML_TYPE.TEXT:
xw.text(node);
break;
default:
throw new Error('Can not perform atomic write for XML type "' + type + '".');
}
}
/**
* @param {XMLWriter} xw
* @param {NodeSet} nset
* @private
*/
function processNodeSet(xw, nset) {
var idx, node;
function writeAttr(attr) {
xw.writeAttribute(attr, node.attr(attr));
}
for (idx = 0, node = nset.eq(0); node !== null; idx++, node = nset.eq(idx)) {
if (node instanceof Tag) {
xw.startElement(node.name);
Object
.keys(node.attrs)
.forEach(writeAttr);
processNodeSet(xw, node);
xw.endElement();
} else {
writeXMLAtomicType(xw, node);
}
}
}
/**
* @param {NodeSet} nset
* @param {Object} options
*/
function serialize(nset, options) {
if ( ! (nset instanceof NodeSet)) {
throw new Error( 'Only NodeSet can be serialized.');
}
if (typeof options !== 'object' || options === null) {
options = {};
}
var xw = new XMLWriter(options.pretty);
if (options.header !== false) {
xw.startDocument();
}
processNodeSet(xw, nset);
return xw.toString();
}
module.exports = {
serialize : serialize
};