Skip to content

Commit

Permalink
Add support for parsing CDATA to SaxLtx (#109)
Browse files Browse the repository at this point in the history
  • Loading branch information
timdp authored and sonnyp committed Feb 12, 2017
1 parent 6d351f3 commit ff770ee
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
22 changes: 19 additions & 3 deletions lib/parsers/ltx.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ var STATE_ATTR_NAME = 5
var STATE_ATTR_EQ = 6
var STATE_ATTR_QUOT = 7
var STATE_ATTR_VALUE = 8
var STATE_CDATA = 9

var SaxLtx = module.exports = function SaxLtx () {
EventEmitter.call(this)
Expand Down Expand Up @@ -73,13 +74,27 @@ var SaxLtx = module.exports = function SaxLtx () {
attrs = {}
}
break
case STATE_CDATA:
if (c === 93 /* ] */ && data.substr(pos + 1, 2) === ']>') {
var cData = endRecording()
if (cData) {
this.emit('text', unescapeXML(cData))
}
state = STATE_IGNORE_COMMENT
}
break
case STATE_TAG_NAME:
if (c === 47 /* / */ && recordStart === pos) {
recordStart = pos + 1
endTag = true
} else if (c === 33 /* ! */) {
recordStart = undefined
state = STATE_IGNORE_COMMENT
if (data.substr(pos + 1, 7) === '[CDATA[') {
recordStart = pos + 8
state = STATE_CDATA
} else {
recordStart = undefined
state = STATE_IGNORE_COMMENT
}
} else if (c === 63 /* ? */) {
recordStart = undefined
state = STATE_IGNORE_INSTRUCTION
Expand All @@ -93,7 +108,8 @@ var SaxLtx = module.exports = function SaxLtx () {
if (c === 62 /* > */) {
var prevFirst = data.charCodeAt(pos - 1)
var prevSecond = data.charCodeAt(pos - 2)
if (prevFirst === 45 /* - */ && prevSecond === 45 /* - */) {
if ((prevFirst === 45 /* - */ && prevSecond === 45 /* - */) ||
(prevFirst === 93 /* ] */ && prevSecond === 93 /* ] */)) {
state = STATE_TEXT
}
}
Expand Down
24 changes: 24 additions & 0 deletions test/cdata-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'use strict'

var vows = require('vows')
var assert = require('assert')
var ltx = require('..')
var parsers = require('../lib/parsers')

var Parser = parsers.find(function (parser) {
return (parser.name === 'SaxLtx')
})

var parse = function (s) {
return ltx.parse(s, {Parser: Parser})
}

vows.describe('sax_ltx').addBatch({
'CDATA parsing': {
'issue-19: parse CDATA content as text': function () {
var el = parse('<root><![CDATA[Content]]></root>')
assert.equal(el.name, 'root')
assert.equal(el.getText(), 'Content')
}
}
}).export(module)

0 comments on commit ff770ee

Please sign in to comment.