Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const fs = require('fs');
- const {Parser} = require('node-expat');
- const {Writable} = require('stream');
- class XMLParser extends Writable {
- constructor() {
- super();
- this.stages = [''];
- this.parser = new Parser('UTF-8');
- this.elements = [];
- this.findingState = {
- startElement: (tag, attributes) => {
- this.stages.push(tag);
- const path = this.stages.join('/');
- if (this.events.includes(path)) {
- this.recordingState.startElement(tag, attributes);
- this.currentState = this.recordingState;
- }
- },
- text: () => {
- // nothing
- },
- endElement: (tag) => {
- this.stages.pop();
- }
- }
- this.recordingState = {
- startElement: (tag, attributes) => {
- const element = {
- "tag": tag,
- "attributes": attributes,
- "nodes": {},
- "text": "",
- };
- if (this.elements.length > 0) {
- const {nodes} = this.getLastElement();
- nodes[tag] = nodes[tag] || [];
- nodes[tag].push(element);
- }
- this.elements.push(element);
- },
- text: (text) => {
- this.getLastElement().text += text.trim();
- },
- endElement: (tag) => {
- const element = this.elements.pop();
- if (this.elements.length === 0) {
- const path = this.stages.join('/');
- this.emit(path, element);
- this.findingState.endElement(tag);
- this.currentState = this.findingState;
- }
- }
- }
- this.currentState = this.findingState;
- this.parser.on('startElement', (...args) => this.currentState.startElement(...args));
- this.parser.on('endElement', (...args) => this.currentState.endElement(...args));
- this.parser.on('text', (...args) => this.currentState.text(...args));
- this.parser.on('error', (error) => {
- })
- }
- on(eventName, listener) {
- super.on(eventName, listener);
- this.events = this.eventNames();
- }
- getLastElement() {
- return this.elements[this.elements.length - 1];
- }
- _write(chunk, encoding, callback) {
- this.parser.write(chunk);
- callback();
- }
- }
- const xmlParser = new XMLParser();
- xmlParser.on('/root/date', (ctx) => {
- console.log(JSON.stringify(ctx));
- });
- xmlParser.on('/root/categories/category', (ctx) => {
- //console.log(JSON.stringify(ctx));
- });
- xmlParser.on('/root/products/product', (ctx) => {
- //console.log(JSON.stringify(ctx));
- });
- xmlParser.parser.on('startElement', (name, attributes) => {
- if (name === 'root') {
- console.log(attributes['targetNamespace']);
- }
- })
- const stream = fs.createReadStream('file.xml');
- stream.pipe(xmlParser);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement