当前位置: 首页 > 工具软件 > htmlparser2 > 使用案例 >

nodejs xml 转json htmlparser2

曾嘉瑞
2023-12-01
let htmlparser = require("htmlparser2");
let fs = require("fs");


function WriteXml(xml) {
    this.xml = xml;
    this.stack = [];
    this.node = "";
    this.rootName = '';
}


WriteXml.prototype = {
    parser() {
        let _self = this;
        let parser = new htmlparser.Parser({
            ontext: function (text) {
                if (text != null && text.trim() != "") {
                    _self.node.Value = text
                }
            },
            onopentag: function (name, attribs) {
                _self.node = {};
                _self.node.Name = name;
                _self.node.Attributes = attribs;
                _self.stack.push(_self.node);
            },
            onclosetag: function (tagname) {
                let pNode = _self.stack.pop();
                if (_self.stack.length == 0) {
                    _self.rootName = pNode;
                } else {
                    let parentNode = _self.stack[_self.stack.length - 1];
                    if (!parentNode.Childs) parentNode.Childs = [];
                    parentNode.Childs.push(pNode);
                }
            }
        }, {
            lowerCaseTags: false,
            decodeEntities: true,
            xmlMode: true
        });
        parser.write(_self.xml)
        parser.end();
        return _self.rootName
    }
}
 类似资料: