1 | 'use strict';
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | const lang = require('zero-lang');
|
8 | const sanitize = require('./sanitize');
|
9 |
|
10 | function filterNodes(nodes) {
|
11 |
|
12 | nodes = nodes || [];
|
13 | return lang.filter(nodes, (node) => !(node.nodeType === 7 && node.target === 'xml'));
|
14 | }
|
15 |
|
16 | function dom2js(doc) {
|
17 | const obj = {
|
18 |
|
19 | type: doc.nodeType,
|
20 | };
|
21 |
|
22 |
|
23 | if (obj.type === 8 ) obj.data = doc.data;
|
24 | if (obj.type === 3 ) obj.text = sanitize(doc.textContent);
|
25 | if (obj.type === 7 ) {
|
26 | obj.tag = doc.target;
|
27 | obj.data = doc.data;
|
28 | }
|
29 |
|
30 |
|
31 | if (doc.tagName) obj.tag = doc.tagName;
|
32 | if (doc.childNodes && doc.childNodes.length) {
|
33 | obj.children = lang.map(filterNodes(doc.childNodes), (child) => dom2js(child));
|
34 | }
|
35 | if (doc.attributes) {
|
36 | obj.attributes = {};
|
37 | lang.each(doc.attributes || [], (attr) => {
|
38 | const name = attr.name;
|
39 | obj.attributes[name] = doc.getAttribute(name);
|
40 | });
|
41 | }
|
42 | return obj;
|
43 | }
|
44 |
|
45 | module.exports = dom2js;
|