Created
May 20, 2020 09:03
-
-
Save Elevista/0dc59dbf8259cc56ee4caa222fbf39ce to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const htmlparser2 = require('htmlparser2') | |
const define = (src, ...args) => { | |
if (!args.length) args.push(src) | |
const [configurable, enumerable] = [true, false] | |
args.forEach(obj => { | |
const keys = Object.entries(obj) | |
.map(([key, value]) => ({ [key]: { value, configurable, enumerable } })) | |
Object.defineProperties(src, Object.assign(...keys)) | |
}) | |
return src | |
} | |
module.exports = xml => { | |
const tags = [{ $children: [] }] | |
const parser = new htmlparser2.Parser({ | |
onopentag ($tag, $attrs) { | |
const [cur] = tags | |
const item = define({ $tag, $children: [], $attrs }) | |
cur.$children.push(item) | |
if (!cur[$tag]) cur[$tag] = item | |
tags.unshift(item) | |
}, | |
ontext ($text) { define(tags[0], { $text }) }, | |
onclosetag ($tag) { | |
if (tags[0].$tag !== $tag) throw Error('parse error') | |
const { $children, $text } = tags.shift() | |
if ($children.length > 0) return | |
const [parent] = tags | |
parent[$tag] = ($text === null || isNaN($text)) ? $text : +$text | |
} | |
}, { xmlMode: true }) | |
parser.write(xml) | |
parser.end() | |
return tags.length > 1 ? tags : tags[0] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment