How to use fast-xml-parser - 10 common examples

To help you get started, we’ve selected a few fast-xml-parser 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 matrix-org / matrix-bifrost / test / xmppjs / test_Stanzas.ts View on Github external
function assertXML(xml) {
    const err = parser.validate(xml);
    if (err !== true) {
        // console.error(xml);
        throw new Chai.AssertionError(err.err.code + ": " + err.err.msg);
    }
}
github magda-io / magda / magda-web-client / src / helpers / xmlToTabular.ts View on Github external
export default function(xmlData: string) {
    // when a tag has attributes
    const options = {
        attrPrefix: "@_",
        textNodeName: "#text",
        ignoreNonTextNodeAttr: true,
        ignoreTextNodeAttr: true,
        ignoreNameSpace: true,
        ignoreRootElement: false,
        textNodeConversion: true,
        textAttrConversion: false
    };
    if (fastXmlParser.validate(xmlData) === true) {
        //optional
        const jsonObj = fastXmlParser.parse(xmlData, options);
        var array = jsonToArray(jsonObj);
        const data = {
            data: array,
            meta: {
                fields: ["name", "value"],
                type: "tabular"
            }
        };
        return data;
    }
    return null;
}
github jimmykane / quantified-self-lib / src / events / adapters / importers / suunto / importer.suunto.sml.ts View on Github external
static getFromXML(contents: string, name = 'New Event'): Promise {
    const json = parser.parse(contents).sml;

    // debugger;

    //  A few mods here to convert it to compatible json suunto string
    json.DeviceLog.Samples = json.DeviceLog.Samples.Sample;

    const samplesWithUTC: any[]  =  json.DeviceLog.Samples.filter((sample: any) => !!sample.UTC);

    // Find the first UTC timestamped sample and use it later for start date
    const startDate = samplesWithUTC.length ? new Date(samplesWithUTC[0].UTC) : new Date(json.DeviceLog.Header.DateTime);


    // Determine the end date
    const endDate = samplesWithUTC.length > 1 ? samplesWithUTC[samplesWithUTC.length - 1].UTC : (new Date((startDate.getTime() + json.DeviceLog.Header.Duration * 1000)));

    // Filter out the old activity type
github DrewML / scd / src / magentoFS.ts View on Github external
async function getModuleConfig(root: string, path: string): Promise {
    const configPath = join(root, path, 'etc', 'module.xml');
    const rawConfig = await fs.readFile(configPath, 'utf8');
    const parsedConfig = parse(rawConfig, {
        ignoreAttributes: false,
        attributeNamePrefix: '',
        ignoreNameSpace: true,
    });

    const config = {
        moduleID: parsedConfig.config.module.name as string,
        sequence: [] as string[],
        pathFromStoreRoot: join(sep, path),
    };
    const { sequence } = parsedConfig.config.module;

    if (!sequence) return config;

    if (Array.isArray(sequence.module)) {
        // multiple dependencies
github jamhall / s3rver / lib / s3rver.js View on Github external
configureBuckets,
      ...serverOptions
    } = defaults({}, options, S3rver.defaultOptions);
    this.serverOptions = serverOptions;
    this._configureBuckets = configureBuckets;
    this.silent = silent;
    this.resetOnClose = resetOnClose;
    this.allowMismatchedSignatures = allowMismatchedSignatures;
    this.store = this.context.store = new FilesystemStore(directory);

    // Log all requests
    this.use(loggerMiddleware(this, silent));

    try {
      // encode object responses as XML
      const parser = new xmlParser.j2xParser({
        ignoreAttributes: false,
        attrNodeName: '@',
        tagValueProcessor: a => he.escape(a.toString()),
      });
      this.use(async (ctx, next) => {
        await next();
        if (isPlainObject(ctx.body)) {
          ctx.type = 'application/xml';
          ctx.body =
            '\n' + parser.parse(ctx.body);
        }
      });

      // Express mount interop
      this.use((ctx, next) => {
        ctx.mountPath = ctx.mountPath || ctx.req.baseUrl;
github XGHeaven / nos-node-sdk / src / client.ts View on Github external
protected async _request(method: string, headers: any, resource: Resource, body?: any): Promise {
    headers['date'] = new Date().toUTCString()

    const uri = getResourceUri(resource)

    // 并不知道设置错误的 content-type 会有什么影响,但是设置了就没错
    if (body) {
      if (typeof body === 'object' && body.constructor === Object) {
        body = new j2xParser({}).parse(CamelCaseObject(body))
        headers['content-type'] = 'application/xml;charset=UTF-8'
      } else {
        headers['content-type'] = mime.getType(uri) || 'application/octet-stream'
      }
    }

    if (body instanceof Buffer || typeof body === 'string') {
      headers['content-md5'] = md5sum(body)
      headers['content-length'] = headers['content-length'] || body.length
    }

    const sign = signature(this.options.accessSecret, method, headers, resource)
    headers['authorization'] = `NOS ${this.options.accessKey}:${sign}`

    return await fetch(url.resolve(this.options.endpoint, uri), {
      method,
github BrainJS / brain.js / __tests__ / utilities / to-svg.js View on Github external
it('should return valid xml when sane inputs provided', () => {
      expect(parser.validate(toSVG(network, options))).toBe(true);
    });
  });
github stoplightio / prism / test-harness / helpers.ts View on Github external
test: (contentType: string, content: string) => {
    const doesContentTypeMatch = !!typeIs.is(contentType, [
      'application/xml',
      'application/*+xml',
      'text/xml',
    ]);
    const isContentXML = parser.validate(content) === true;

    return doesContentTypeMatch || isContentXML;
  },
  validate: (expected: Result, output: Result) => {
github lmmfranco / nintendo-switch-eshop / src / nintendo-switch-eshop.ts View on Github external
export const getGamesJapan = async (): Promise => {
  try {
    const gamesJP = await fetch(constants.JP_GET_GAMES_URL);

    if (!gamesJP.ok) throw new Error('JP_games_request_failed');

    const parsedGamesJP = xml2json(await gamesJP.text());

    const allGamesJP: interfaces.GameJP[] = parsedGamesJP.TitleInfoList.TitleInfo;

    return allGamesJP;
  } catch (err) {
    if (/(?:JP_games_request_failed)/i.test(err.toString())) throw new constants.EshopError('Fetching of JP Games failed');
    throw err;
  }
};
github NaturalIntelligence / Stubmatic / index.js View on Github external
function validateSyntax(fileName) {
	try {
		if (fileName.endsWith(".json")) {
			require('jsonlint').parse(fs.readFileSync(fileName, {
				encoding: 'utf-8'
			}));
			console.log("Validated successfully");
		} else if (fileName.endsWith(".yaml") || fileName.endsWith(".yml")) {
			require('yamljs').parseFile(fileName);
			console.log("Validated successfully");
		}else if(fileName.endsWith(".xml")){
			var result = require('fast-xml-parser').validate(fs.readFileSync(fileName, {
				encoding: 'utf-8'
			}));
			if(result === true) {
				console.log("Validated successfully");
			}else{
				console.log("Validation failed");
			}
		}else {
			console.log("Unsupported file");
		}
	} catch (e) {
		console.log("Validation failed");
		console.log(color(e, 'red'));
		//if(e.line) console.log("line number: " + e.line + ":" + e.column);
	}
}

fast-xml-parser

Validate XML, Parse XML, Build XML without C/C++ based libraries

MIT
Latest version published 1 month ago

Package Health Score

91 / 100
Full package analysis