This repository has been archived by the owner on Aug 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
print.js
93 lines (75 loc) · 2.15 KB
/
print.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
const { readFileSync } = require('fs')
const SaxParser = require('..')
const parser = new SaxParser()
const INDENT_SIZE = 4
const INDENT = ' '.repeat(INDENT_SIZE)
const isEmptyObject = (obj) =>
Object.keys(obj).length === 0 && obj.constructor === Object
const indent = (depth) => {
for (let i = 0; i < depth; ++i) process.stdout.write(INDENT)
}
let depth = 0
parser.on('startElement', (name, attrs) => {
indent(depth)
process.stdout.write(`<${name}`)
if (!isEmptyObject(attrs)) {
process.stdout.write(' ')
for (const key in attrs) {
process.stdout.write(`${key}="${attrs[key]}" `)
}
}
process.stdout.write('>\n')
depth++
})
parser.on('text', (text) => {
indent(depth)
process.stdout.write(text + '\n')
})
parser.on('endElement', (name) => {
depth--
indent(depth)
process.stdout.write(`</${name}>\n`)
})
parser.on('startAttribute', (attr) => {
// console.log('startAttribute', attr)
})
parser.on('endAttribute', () => {
// console.log('endAttribute')
})
parser.on('cdata', (cdata) => {
indent(depth)
process.stdout.write(`<![CDATA[${cdata}]]>\n`)
})
parser.on('comment', (comment) => {
process.stdout.write(`<!--${comment}-->\n`)
})
parser.on('doctype', (doctype) => {
process.stdout.write(`<!DOCTYPE ${doctype}>\n`)
})
parser.on('startDocument', () => {
process.stdout.write(`<!--=== START ===-->\n`)
})
parser.on('endDocument', () => {
process.stdout.write(`<!--=== END ===-->`)
})
parser.on('error', ({ code, offset }) => {
console.error('parse error: code=%s | offset=[%s]', code, offset)
})
parser.on('startXmlDeclAttr', (declAttr) => {
// console.log('startXmlDeclAttr', declAttr)
})
parser.on('endXmlDeclAttr', () => {
// console.log('endXmlDeclAttr')
})
parser.on('xmlDecl', (decl) => {
process.stdout.write('<?xml ')
for (const key in decl) {
process.stdout.write(`${key}="${decl[key]}" `)
}
process.stdout.write('?>\n')
})
parser.on('processingInstruction', (pi) => {
process.write(`<?${pi.target} ${pi.instruction}?>`)
})
const xml = readFileSync(__dirname + '/../benchmark/test.xml', 'utf-8')
parser.parse(xml)