How to use xml2js - 10 common examples

To help you get started, we’ve selected a few xml2js 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 elastic / kibana / packages / kbn-test / src / failed_tests_reporter / get_failures.ts View on Github external
export async function getFailures(log: ToolingLog, testReportPath: string) {
  const xml = await readAsync(testReportPath, 'utf8');

  // Parses junit XML files
  const report: TestReport = await xml2js.parseStringPromise(xml);

  // Grab the failures. Reporters may report multiple testsuites in a single file.
  const testSuites = 'testsuites' in report ? report.testsuites.testsuite : [report.testsuite];

  const failures: TestFailure[] = [];
  for (const testSuite of testSuites) {
    for (const testCase of testSuite.testcase) {
      const { failure } = testCase;

      if (!failure) {
        continue;
      }

      // unwrap xml weirdness
      const failureCase: TestFailure = {
        ...testCase.$,
github axlemax / sfdx / cmd / deployFlows.js View on Github external
errorMsg += '\n' + fileError
      if (!argv.quiet) console.error(fileError)
      return { stderr: errorMsg }
    }
  } else {
    // No flow directory
    return {}
  }

  const flowDefs = []
  const regexDefFilename = /.+(?=\.flowDefinition-meta\.xml)/
  for (const defFile of defFileList) {
    const defFilename = regexDefFilename.exec(defFile)[0]

    // Get active version number from definition files
    const parser = new xml2js.Parser()
    const fileData = await fs.readFileSync(joinPath(defPath, defFile))
    parser.parseString(fileData, (err, result) => {
      const defVersion = parseInt(result['FlowDefinition']['activeVersionNumber'])
      flowDefs[defFilename] = { activeVersion: defVersion }
    })
  }

  // For the filename, look at everything until '-' followed by a number
  const regexFlowFilename = /.+?(?=-[0-9]+\.)/

  let flowFile = ''
  let flowsToKeep = config.inactiveFlowsToKeep

  if (isNaN(flowsToKeep)) {
    console.error(err('Invalid number of flows specified in configuration.'))
    process.exit(1)
github le-doux / bitsy / experiments / font / arabic2-bitsy / ttx_to_bitsyfont.js View on Github external
fs.readFile("bitsy-with-arabic.ttx", "utf8", function(err, data) {
	// console.log(data);
	// console.log(xml2js);
	xml2js.parseString(data, function(err, result) {
		var bitsyFontData = "FONT arabic\n";

		var font = result.ttFont;

		var head = font.head[0];
		function getHeadValue(id) {
			return head[id][0]["$"]["value"];
		}

		var unitsPerEm = getHeadValue("unitsPerEm");
		var pixelsPerEm = getHeadValue("lowestRecPPEM");
		// 8 / 4096 = 0.001953125
		// 4096 / 8 = 512
		var pixelsPerUnit = pixelsPerEm / unitsPerEm; // pixelsPerUnit = 0.001953125
		var unitsPerPixel = unitsPerEm / pixelsPerEm; // unitsPerPixel = 512
github Trevelopment / MZD-AIO / app / assets / js / messages-settings.js View on Github external
/* jshint esversion:6, -W117, -W116 */
var xml2js = require('xml2js')
// var settingsData = new Config({ 'name': 'msgSettings' })
var data2edit, msgLangs = [],
  currLangMsgs = []
var currMsgLang
var parser = new xml2js.Parser()

function getMsgLangs () {
  var messageFile = (fs.existsSync(`${varDir}/message_replies/jci/settings/configurations/blm_msg-system.xml`) ? `${varDir}` : `${builddir}/config`)
  messageFile += `/message_replies/jci/settings/configurations/blm_msg-system.xml`
  fs.readFile(path.resolve(messageFile), function (err, data) {
    if (err) console.log(err)
    parser.parseString(data, function (err, result) {
      if (err) console.log(err)
      if (data2edit !== result) {
        data2edit = result
        //   console.dir(data2edit.Node.Node[0].Node[0].$.key)
        for (var x in data2edit.Node.Node[0].Node) msgLangs.push(data2edit.Node.Node[0].Node[x].$.key)
        // getMsgsForLang(msgLangs[currentMsgLang])
        // console.dir(msgLangs)
        // return msgLangs
      }
github hyurl / cool-node / Core / Middleware / HttpXMLHandler.js View on Github external
const bodyParser = require('body-parser');
const xml2js = require("xml2js");

var plain = /text\/plain\b/,
    xml = /(text|application)\/xml\b/,
    builder = new xml2js.Builder({ cdata: true });

module.exports = (app) => {
    app.use(bodyParser.text({
        type: (req) => {
            // Parse plain/XML.
            var type = req.headers['content-type'];
            return plain.test(type) || xml.test(type);
        }
    })).use((req, res, next) => {
        // Add a method on response object, used for sending XML to the client.
        res.xml = (data) => {
            if (!res.get("Content-Type")) {
                res.type("xml");
            }
            if (data !== null && data !== undefined) {
                if (typeof data == "string") {
github webinos / Webinos-Platform / webinos / core / manager / widget_manager / lib / manifest2policy / manifest2policy.js View on Github external
var manifest2policy = function(manifestFile, appId, features) {
        var manifest = null;

        try {
            var xmlManifest = fs.readFileSync(manifestFile);
            // Load xml parser
            var xmlParser = new xml2js.Parser(xml2js.defaults["0.2"]);
            // Parse manifest
            xmlParser.parseString(xmlManifest, function(err, data) {
                if (err === undefined || err === null) {
                    manifest = data['widget'];
                } else {
                    console.log(err);
                    return '';
                }
            });
        } catch (error) {
            console.log(error);
            return '';
        }

        // target
        var target = [];
github dominickp / JMF-Subscription / JmfSubscriptionServer.js View on Github external
request.on('end', function () {
        // Attempt to parse the XML
        parseString(body, {trim: true}, function (err, result) {
            // Log the body of the request
            //var jsonResult = JSON.parse(result);
            
            var fullResult = util.inspect(result, false, null);
            
            if(err){
                winston.error("Parse error" + err);
            }
            
            if(typeof result["JMF"]["Signal"][0]["DeviceInfo"] !== 'undefined'){
                winston.info('Subscription Update', { 
                        DeviceID: result["JMF"]["Signal"][0]["DeviceInfo"][0]["$"]["DeviceID"],
                        DeviceStatus: result["JMF"]["Signal"][0]["DeviceInfo"][0]["$"]["DeviceStatus"],
                        StatusDetails: result["JMF"]["Signal"][0]["DeviceInfo"][0]["$"]["StatusDetails"],
                        ProductionCounter: result["JMF"]["Signal"][0]["DeviceInfo"][0]["$"]["ProductionCounter"]
                    }
github boopathi / react-svg-loader / index.js View on Github external
module.exports = function(content) {

  this.cacheable && this.cacheable(true);
  this.addDependency(this.resourcePath);

  var loaderContext = this;
  var callback = this.async();

  var parser = new xml2js.Parser({
    normalize: true,
    normalizeTags: true
  });

  var builder = new xml2js.Builder({
    headless: true
  });

  parser.addListener('error', function(err) {
    callback(err);
  });

  parser.addListener('end', function(result) {
    var svg = result.svg;
    var allowedAttrs = ['d', 'id', 'width', 'height', 'style'];
    // $ is the list of attrs
    var allowedTags = svgElements.concat(['$']);
    var filtered = traverse(result, function(value, key, parent, parentKey) {
      if ('number' === typeof key) return true;
      if (parentKey === '$') return allowedAttrs.indexOf(key) > -1;
      return allowedTags.indexOf(key) > -1;
github NativeScript / nativescript-cli / lib / services / android-plugin-build-service.ts View on Github external
packageName = xml["manifest"]["$"]["package"];
			}

			// set the xml as the value to iterate over its properties
			xml = xml["manifest"];
		}

		// if the manifest file doesn't have a  scope, only the first setting will be picked up
		const newManifest: any = { manifest: {} };
		for (const prop in xml) {
			newManifest.manifest[prop] = xml[prop];
		}

		newManifest.manifest["$"]["package"] = packageName;

		const xmlBuilder = new Builder();
		const newManifestContent = xmlBuilder.buildObject(newManifest);

		return newManifestContent;
	}
github meetearnest / aws-sts / src / index.js View on Github external
function *selectRole(samlAssertion, roleName) {
  let buf = new Buffer(samlAssertion, 'base64');
  let saml = yield thunkify(xml2js.parseString)(
    buf,
    {tagNameProcessors: [xml2js.processors.stripPrefix], xmlns: true});

  // Extract SAML roles
  let roles;
  let attributes = saml.Response.Assertion[0].AttributeStatement[0].Attribute;
  for (let attribute of attributes) {
    if (attribute.$.Name.value === 'https://aws.amazon.com/SAML/Attributes/Role') {
      roles = attribute.AttributeValue.map(function (role) {
        return parseRoleAttributeValue(role._);
      });
    }
  }

  if (!roles || roles.length <= 0) {
    throw new Error('No roles are assigned to your SAML account. Please contact Ops.');
  }