How to use sax - 10 common examples

To help you get started, we’ve selected a few sax examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github danja / seki / srx2map.js View on Github external
// sax settings
var strict = true; // set to false for html-mode
var options = {};

// flag for position in XML  ...here if true ... 
var inBinding = false;

// values to extract from the XML
var element = "";
var bindingName = "";
var bindingValue = "";
var bindingType = "";

// create a stream parser
var saxStream = sax.createStream(strict, options);

// make it available to other scripts
exports.createStream = function() {
    return saxStream;
};

// minimal parse error handling
saxStream.on("error", function(e) {
    console.error("SAX parse error", e);
});

// handle an opening tag
// loosely corresponds to SAX startElement(...)
saxStream.on("opentag", function(node) {

    element = node.name;
github danmactough / node-feedparser / lib / feedparser / index.js View on Github external
TransformStream.call(this);
  this._readableState.objectMode = true;
  this._readableState.highWaterMark = 16; // max. # of output nodes buffered

  this.init();

  // Parse options
  this.options = _.assign({}, options);
  if (!('strict' in this.options)) this.options.strict = false;
  if (!('normalize' in this.options)) this.options.normalize = true;
  if (!('addmeta' in this.options)) this.options.addmeta = true;
  if (!('resume_saxerror' in this.options)) this.options.resume_saxerror = true;
  if ('MAX_BUFFER_LENGTH' in this.options) {
    sax.MAX_BUFFER_LENGTH = this.options.MAX_BUFFER_LENGTH; // set to Infinity to have unlimited buffers
  } else {
    sax.MAX_BUFFER_LENGTH = 16 * 1024 * 1024; // 16M versus the 64K default
  }
  if (this.options.feedurl) this.xmlbase.unshift({ '#name': 'xml', '#': this.options.feedurl});

  // See https://github.com/isaacs/sax-js for more info
  this.stream = sax.createStream(this.options.strict /* strict mode - no by default */, {lowercase: true, xmlns: true });
  this.stream.on('error', this.handleSaxError.bind(this));
  this.stream.on('processinginstruction', this.handleProcessingInstruction.bind(this));
  this.stream.on('opentag', this.handleOpenTag.bind(this));
  this.stream.on('closetag',this.handleCloseTag.bind(this));
  this.stream.on('text', this.handleText.bind(this));
  this.stream.on('cdata', this.handleText.bind(this));
  this.stream.on('end', this.handleEnd.bind(this));
}
util.inherits(FeedParser, TransformStream);
github dtjohnson / xlsx-populate / src / XmlParser.ts View on Github external
return new Promise((resolve, reject) => {
            // Create the SAX parser.
            const parser = new SAXParser(true);

            // Parsed is the full parsed object. Current is the current node being parsed. Stack is the current stack of
            // nodes leading to the current one.
            let parsed: INode, current: INode;
            const stack: INode[] = [];

            // On error: Reject the promise.
            parser.onerror = reject;

            // On text nodes: If it is all whitespace, do nothing. Otherwise, try to convert to a number and add as a child.
            parser.ontext = text => {
                if (allWhitespaceRegex.test(text)) {
                    if (current && current.attributes && current.attributes['xml:space'] === 'preserve') {
                        if (!current.children) current.children = [];
                        current.children.push(text);
                    }
github Cap32 / wxml-loader / src / index.js View on Github external
const isSourceAbsolute = isAbsolute(source);
		if (!isSourceAbsolute && !hasProcotol(source)) {
			source = ensureStartsWithDot(source);
		}
		if (enforceRelativePath && isSourceAbsolute) {
			source = ensureRelativePath(source);
		}

		/* istanbul ignore else */
		if (typeof transformUrl === 'function') {
			source = transformUrl(source, resource);
		}
		content = replaceAt(content, startIndex, endIndex, source);
	};

	const parser = sax.parser(false, { lowercase: true });

	parser.onattribute = ({ name, value }) => {
		if (
			!value ||
			!isSrc(name) ||
			isDynamicSrc(value) ||
			!isUrlRequest(value, root)
		) {
			return;
		}

		const endIndex = parser.position - 1 - ROOT_TAG_LENGTH;
		const startIndex = endIndex - value.length;
		const request = urlToRequest(value, root);

		requests.unshift({ request, startIndex, endIndex });
github lula / ngx-soap / src / libts / wsdl.ts View on Github external
xmlToObject(xml: any, callback?: any) {
    var self = this;
    // var p = typeof callback === 'function' ? {} : saxParser(true, {});
    var p = sax.parser(true, {});
    var objectName: any = null;
    var root: any = {};
    var schema: any = {
      Envelope: {
        Header: {
          Security: {
            UsernameToken: {
              Username: 'string',
              Password: 'string'
            }
          }
        },
        Body: {
          Fault: {
            faultcode: 'string',
            faultstring: 'string',
github itteco / iframely / lib / iframely-meta.js View on Github external
function xmlStream2oembed(stream, callback) {
        var oembed;
        var prop;
        var value;
        var firstTag;

        var charset = getCharset(stream.headers && stream.headers['content-type']);

        var saxStream = sax.createStream();
        saxStream.on('error', function(err) {
            callback(err);
        });
        saxStream.on('opentag', function(tag) {
            if (!firstTag) {
                // Should be HEAD but HASH tag found on qik.
                firstTag = tag.name;
                oembed = {};
            } else if (oembed) {
                prop = tag.name.toLowerCase();
                value = "";
            }
        });
        saxStream.on('text', function(text) {
            if (prop) value += text;
        });
github vpulim / node-soap / src / wsdl / index.ts View on Github external
} else {
            value = top.object + text;
          }
        }
      }

      if (top.object[this.options.attributesKey]) {
        top.object[this.options.valueKey] = value;
      } else {
        top.object = value;
      }
    };

    if (typeof callback === 'function') {
      // we be streaming
      const saxStream = sax.createStream(true, null);
      saxStream.on('opentag', p.onopentag);
      saxStream.on('closetag', p.onclosetag);
      saxStream.on('cdata', p.oncdata);
      saxStream.on('text', p.ontext);
      xml.pipe(saxStream)
      .on('error', (err) => {
        callback(err);
      })
      .on('end', () => {
        let r;
        try {
          r = finish();
        } catch (e) {
          return callback(e);
        }
        callback(null, r);
github exceljs / exceljs / lib / stream / xlsx / worksheet-reader.js View on Github external
const {sharedStrings} = this.workbook;
    const {styles} = this.workbook;
    const {properties} = this.workbook;

    // xml position
    let inCols = false;
    let inRows = false;
    let inHyperlinks = false;

    // parse state
    let cols = null;
    let row = null;
    let c = null;
    let current = null;

    const parser = Sax.createStream(true, {});
    parser.on('opentag', node => {
      if (emitSheet) {
        switch (node.name) {
          case 'cols':
            inCols = true;
            cols = [];
            break;
          case 'sheetData':
            inRows = true;
            break;

          case 'col':
            if (inCols) {
              cols.push({
                min: parseInt(node.attributes.min, 10),
                max: parseInt(node.attributes.max, 10),
github racker / glimpse.js / grunt / tasks / compile-svg.js View on Github external
function processFile(filePath) {
        // Read in an SVG file.
        var readStream = fs.createReadStream(filePath),
            saxStream = sax.createStream(false,
              { normalize: true, lowercase: true }),
            indent = 2;

        saxStream.on('error', function() {
          grunt.log.error('Error parsing SVG file.');
        });

        saxStream.on('end', function() {
          fileReadCount += 1;
          if (fileCount === fileReadCount) {
            wrapEnd(writeStream);
            writeStream.destroySoon();
          }
        });

        // Write out open tags and attrs if not ignored.
github JpEncausse / WSRNodeJS / script / vendor / feedparser.js View on Github external
FeedParser.prototype.parseOpts = function (options) {
  this.options = options || {};
  if (!('strict' in this.options)) this.options.strict = false;
  if (!('normalize' in this.options)) this.options.normalize = true;
  if (!('addmeta' in this.options)) this.options.addmeta = true;
  if (!('resume_saxerror' in this.options)) this.options.resume_saxerror = true;
  if ('MAX_BUFFER_LENGTH' in this.options) {
    sax.MAX_BUFFER_LENGTH = this.options.MAX_BUFFER_LENGTH; // set to Infinity to have unlimited buffers
  } else {
    sax.MAX_BUFFER_LENGTH = 16 * 1024 * 1024; // 16M versus the 64K default
  }
  if (this.options.feedurl) this.xmlbase.unshift({ '#name': 'xml', '#': this.options.feedurl});
};

sax

An evented streaming XML parser in JavaScript

ISC
Latest version published 5 months ago

Package Health Score

76 / 100
Full package analysis