Simple JavaScript Lexer for XML documents
Features
- Very small, fast and simple! (~250 sloc)
- Event driven API (SAX-like)
- Works in Browser, WebWorkers, ServiceWorkers, Node.js or React Native
- Fault tolerant
- Handles CDATA
- Easy to extend and fine tune (state machine is exposed in Lexer instances)
If you are looking for a XML Reader/Parser to convert XML documents into Javascript objects, check my other projects:
Install
npm install --save xml-lexer
Examples
Happy case
const lexer = ; const xml =`<hello color="blue"> <greeting>Hello, world!</greeting></hello>`; lexer;lexer; /*Console output: { type: 'open-tag', value: 'hello' }{ type: 'attribute-name', value: 'color' }{ type: 'attribute-value', value: 'blue' }{ type: 'open-tag', value: 'greeting' }{ type: 'data', value: 'Hello, world!' }{ type: 'close-tag', value: 'greeting' }{ type: 'close-tag', value: 'hello' }*/
Chunked processing
const lexer = ; const chunk1 = `<hello><greet`; // note thisconst chunk2 = `ing>Hello, world!</greeting></hello>`; lexer;lexer;lexer; /*Console output: { type: 'open-tag', value: 'hello' }{ type: 'open-tag', value: 'greeting' }{ type: 'data', value: 'Hello, world!' }{ type: 'close-tag', value: 'greeting' }{ type: 'close-tag', value: 'hello' }*/
Document with errors
const lexer = ; lexer;lexer; /*Console output (note the open-tag value): { type: 'open-tag', value: '<hello"' }{ type: 'data', value: 'hi' }{ type: 'close-tag', value: 'hello' }*/
Update state machine to fix document errors
const Lexer = ;const lexer = Lexer; lexerstateMachineLexerStatetagBeginLexerActionlt = {};lexerstateMachineLexerStatetagNameLexerActionerror = {}; lexer;lexer; /*Console output (note the fixed open-tag value): { type: 'open-tag', value: 'hello' }{ type: 'data', value: 'hi' }{ type: 'close-tag', value: 'hello' }*/
License
MIT