forked from znerol/node-xmlshim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
domwriter.js
105 lines (81 loc) · 2.62 KB
/
domwriter.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
function DOMWriter(writer) {
this.writer = writer;
}
DOMWriter.prototype.writeNode = function(node) {
switch (node.nodeType) {
case node.ELEMENT_NODE:
this.writeElement(node);
break;
case node.ATTRIBUTE_NODE:
this.writeAttribute(node);
break;
case node.TEXT_NODE:
this.writeText(node);
break;
case node.CDATA_SECTION_NODE:
this.writeCdata(node);
break;
case node.COMMENT_NODE:
this.writeComment(node);
break;
case node.DOCUMENT_NODE:
this.writeDocument(node);
break;
case node.DOCUMENT_FRAGMENT_NODE:
this.writeDocumentFragment(node);
break;
default:
console.log('Serialization of node type ' + node.nodeType +
' not supported yet');
break;
}
};
DOMWriter.prototype.writeElement = function(element) {
var i, prefix, nsURI, name, attr;
name = element.nodeName.split(':').slice(-1)[0];
nsURI = element.namespaceURI || undefined;
prefix = element.prefix || undefined;
this.writer.startElementNS(prefix, name, nsURI);
for (i=0; i < element.attributes.length; i++) {
attr = element.attributes[i];
if (attr.name.substr(0, 6) !== 'xmlns:') {
this.writeAttribute(element.attributes[i]);
}
}
for (i=0; i < element.childNodes.length; i++) {
this.writeNode(element.childNodes[i]);
}
this.writer.endElement();
};
DOMWriter.prototype.writeAttribute = function(attribute) {
var name, nsURI, prefix;
name = attribute.name.split(':').slice(-1)[0];
nsURI = attribute.namespaceURI || undefined;
prefix = attribute.prefix || undefined;
this.writer.startAttributeNS(prefix, name, nsURI);
this.writer.writeString(attribute.value);
this.writer.endAttribute();
};
DOMWriter.prototype.writeText = function(text) {
this.writer.writeString(text.data);
};
DOMWriter.prototype.writeCdata = function(cdata) {
this.writer.startCdata();
this.writer.writeString(cdata.data);
this.writer.endCdata();
};
DOMWriter.prototype.writeComment = function(comment) {
this.writer.startComment();
this.writer.writeString(comment.data);
this.writer.endComment();
}
DOMWriter.prototype.writeDocument = function(doc) {
this.writeElement(doc.documentElement);
}
DOMWriter.prototype.writeDocumentFragment = function(docfrag) {
var i;
for (i=0; i < docfrag.childNodes.length; i++) {
this.writeNode(docfrag.childNodes[i]);
}
}
exports.DOMWriter = DOMWriter;