-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfromXmlStr.js
More file actions
62 lines (55 loc) · 1.8 KB
/
fromXmlStr.js
File metadata and controls
62 lines (55 loc) · 1.8 KB
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
// todo: deps.js, mod.js, etc.
import {fnlxml} from 'https://raw.githubusercontent.com/xtao-org/fnlxml/v0.2.0/fnlxml.js'
import {escape} from 'https://cdn.jsdelivr.net/gh/jevko/jevko.js@v0.1.5/mod.js'
// todo: handle HTML entities & hex entities & whathaveyou
export const resolveEntity = (ent) => {
if (ent === '<') return '<'
if (ent === '>') return '>'
if (ent === '"') return '"'
if (ent === ''') return "'"
if (ent === '&') return "&"
if (ent === ' ') return " "
if (ent.startsWith('&#x')) {
const num = Number.parseInt(ent.slice(3, -1), 16)
return String.fromCodePoint(num)
}
// todo?: optimize &#x vs &#
if (ent.startsWith('&#')) {
return String.fromCodePoint(Number.parseInt(ent.slice(2, -1)))
}
throw Error(`Unknown entity: ${ent}`)
}
export const fromXmlStr = (str) => {
let ret = ''
const stream = fnlxml({
emit(name, str_) {
const str = escape(str_)
if (name === 'STagName') ret += `\\${str} [`
else if (name === 'AttValue') ret += str
else if (name === 'Reference') ret += resolveEntity(str)
else if (name === 'Attribute') ret += `]`
else if (name === 'ETagName') ret += `]`
else if (name === 'EETagC') ret += `]`
else if (name === 'CData') ret += str
else if (name === 'CharData') ret += str
else if (name === 'AttName') ret += `${str}=[`
// else if (name === 'AttName') {
// if (hasAttrs === false) {
// hasAttrs = true
// ret += '['
// }
// ret += `${str} [`
// }
// else if (name === 'STagC' || name === 'EETagC') {
// if (hasAttrs) {
// ret += ']'
// hasAttrs = false
// }
// }
// else throw Error('oops' + name)
}
})
stream.chunk(str)
stream.end()
return ret
}