-
Notifications
You must be signed in to change notification settings - Fork 0
/
xml.js
83 lines (71 loc) · 2.2 KB
/
xml.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
const xmldom = require(`@xmldom/xmldom`);
// TODO: trim
exports.getNodeText = function getNodeText(node) {
if (!node) { return ``; }
const serializer = new xmldom.XMLSerializer();
let str = ``;
for (let c = 0; c < node.childNodes.length; c++) {
if (node.childNodes[c].nodeType === 3) {
str += serializer.serializeToString(node.childNodes[c]);
}
}
return str.replace(/\&/g, `&`);
};
exports.setNodeText = function setNodeText(node, val) {
if (!node) {
return;
}
const doc = node.ownerDocument;
const children = node.childNodes;
// find and replace the text node
for (let i = 0, len = children.length; i < len; i++) {
const child = children.item(i);
if (child.nodeType === 3) {
node.replaceChild(doc.createTextNode(val), child);
return;
}
}
// Didn't find it? Create it.
node.appendChild(doc.createTextNode(val));
};
exports.getTagText = function getTagText(node, name) {
const nodes = node.getElementsByTagName(name);
if (nodes && nodes.length) {
return exports.getNodeText(nodes.item(nodes.length - 1));
} else {
return null;
}
};
exports.nodeToString = function nodeToString(node) {
return (new xmldom.XMLSerializer()).serializeToString(node);
};
exports.parseFromString = function parseFromString(str) {
return new xmldom.DOMParser().parseFromString(str);
};
exports.getLastElement = function getLastElement(node, name) {
const nodes = node.getElementsByTagName(name);
return nodes && nodes.length > 0 ? nodes.item(nodes.length - 1) : null;
};
exports.getElementWithAttribute = function getElementWithAttribute(node, name, attr, value) {
const elems = this.doc.documentElement.getElementsByTagName(name);
for (let i = 0, len = elems.length; i < len; i++) {
const elem = elems.item(i);
if (elem.hasAttribute(attr) && elem.getAttribute(attr) === value) {
return elem;
}
}
return null;
};
exports.ensureElement = function ensureElement(node, name) {
let elem = exports.getLastElement(node, name);
if (!elem) {
elem = node.ownerDocument.createElement(name);
node.appendChild(elem);
}
return elem;
};
exports.removeAllChildren = function removeAllChildren(node) {
for (let i = node.childNodes.length - 1; i >= 0; i--) {
node.removeChild(node.childNodes.item(i));
}
};