How to use the Parser function from xml2js

Find comprehensive JavaScript xml2js.Parser code examples handpicked from public code repositorys.

xml2js.Parser is a JavaScript class in the xml2js library that parses an XML string into a JavaScript object, with configurable options and callback functions.

259
260
261
262
263
264
265
266
267
268
var xmlFile = objectsPath + '/' + folderName + '/' + identityFolderName + '/target/target.xml';
var jsonFile = objectsPath + '/' + folderName + '/' + identityFolderName + '/object.json';

if (fs.existsSync(xmlFile)) {
    var resultXML = '';
    xml2js.Parser().parseString(fs.readFileSync(xmlFile, 'utf8'),
        function (err, result) {
            for (var first in result) {
                for (var secondFirst in result[first].Tracking[0]) {
                    resultXML = result[first].Tracking[0][secondFirst][0].$.name;
fork icon14
star icon20
watch icon5

+ 13 other calls in file

558
559
560
561
562
563
564
565
566
567
        }
    }, function (error) {
        QuickLogger.logErrorEvent(getStringTableEntry('Invalid configuration file format', {error: error.toString()}));
    });
} else {
    var xmlParser = new xml2js.Parser();
    fs.readFile(configFile, function(fileError, xmlData) {
        if (fileError == null) {
            xmlParser.parseString(xmlData, function (xmlError, xmlObject) {
                if (xmlError == null) {
fork icon4
star icon10
watch icon4

+ 4 other calls in file

How does xml2js.Parser work?

xml2js.Parser works by taking an XML string as its input and parsing it into a JavaScript object, with configurable options and callback functions. When instantiated, xml2js.Parser creates a new parser object that can be used to parse XML strings into JavaScript objects. The parser object can be configured with various options, such as whether to preserve or discard whitespace, how to handle attributes or CDATA sections, and how to normalize tag names or values. The parser object also provides various callback functions, such as onStartElement and onEndElement, that can be used to handle specific events during the parsing process, such as the start or end of a tag, or the discovery of an attribute or a comment. Once the parser object is configured, the parseString method can be called to parse an XML string into a JavaScript object, represented by a nested set of objects and arrays that correspond to the elements, attributes, and values in the XML. The resulting JavaScript object can then be used to access or manipulate the data in the XML. Note that xml2js.Parser is part of the xml2js library, which provides a fast and flexible parser for XML documents in JavaScript, and supports various parsing options, callback functions, and error handling mechanisms.

10
11
12
13
14
15
16
17
18
19
const { promisify } = require("util");
const { createProxyMiddleware } = require("http-proxy-middleware");
const bodyParser = require("body-parser");
require("body-parser-xml")(bodyParser);
const xml2js = require("xml2js");
const xmlParser = new xml2js.Parser({
  async: false,
  tagNameProcessors: [xml2js.processors.stripPrefix],
});

fork icon0
star icon4
watch icon3

+ 3 other calls in file

17
18
19
20
21
22
23
24
25
26
27
28
const violatingDrones = []; //list of drones that violate the NDZ
const violatingPilots = []; //list of piolts that own drones that violate the NDZ


 async function getDrones() { 
  //this function retrieves xml data from a source, parses the xml into json and creates drone objects to be added to the drone list
  var parser = new xml2js.Parser(); //init xml to json parser


  try {
    const response = await axios.get(dronePositionsURL).then(res =>{ //retrieve xml data from source, waiting for response
      parser.parseString(res.data,function(err,result){ //parse to json
fork icon0
star icon2
watch icon1

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const xml2js = require("xml2js");

const xml = `

John Doe
42

Main St
Anytown

`;

const parser = new xml2js.Parser();

parser.parseString(xml, (err, result) => {
  if (err) {
    console.error(err);
  } else {
    console.log(result);
  }
});

In this example, we first import the xml2js library and define an XML string representing a simple person object with a name, age, and address. We then create a new xml2js.Parser object and call its parseString method to parse the XML string into a JavaScript object, represented by a nested set of objects and arrays that correspond to the elements, attributes, and values in the XML. We also provide a callback function to handle any errors that may occur during the parsing process, and to print the resulting JavaScript object to the console if the parsing succeeds. The output will be a JavaScript object representing the person data in the XML, with properties such as name, age, and address containing nested objects and arrays representing the corresponding elements and values. Note that this is just a simple example, and xml2js.Parser can be used to parse more complex XML documents with various options, callback functions, and error handling mechanisms, such as ignoring or preserving certain elements or attributes, or applying custom parsing rules.

219
220
221
222
223
224
225
226
227
228

// Parsing of Discovery responses taken from my ONVIF-Audit project, part of the 2018 ONVIF Open Source Challenge
// Filter out xml name spaces
xml = xml.replace(/xmlns([^=]*?)=(".*?")/g, "");

const parser = new xml2js.Parser({
  attrkey: "attr",
  charkey: "payload", // this ensures the payload is called .payload regardless of whether the XML Tags have Attributes or not
  explicitCharkey: true,
  tagNameProcessors: [xml2js.processors.stripPrefix], // strip namespace eg tt:Data -> Data
fork icon0
star icon0
watch icon5

+ 2 other calls in file

24
25
26
27
28
29
30
31
32
33
shape = shape || {};

var result = null;
var error = null;

var parser = new xml2js.Parser(options);
parser.parseString(xml, function (e, r) {
  error = e;
  result = r;
});
fork icon0
star icon0
watch icon1

348
349
350
351
352
353
354
355
356
357
async parseXml(xml) {
    try {
        if (!xml)
            return

        const parser = new xml2js.Parser();
        return new Promise((resolve, reject) => {
            parser.parseString(xml, (err, result) => {
                if (err) {
                    reject(err);
fork icon0
star icon0
watch icon1

15
16
17
18
19
20
21
22
23
24
25
26




module.exports = ({ strapi }) => ({
    async parseLogicomXml({ entry, auth }) {
        try {
            // const parser = new xml2js.Parser();
            const importRef = {
                created: 0,
                updated: 0,
                republished: 0,
fork icon0
star icon0
watch icon1

271
272
273
274
275
276
277
278
279
280
281
282
283






const xml2js = require('xml2js');
const fs = require('fs');
const parser = new xml2js.Parser({ attrkey: "attr" });
let xml_string = fs.readFileSync(__dirname + "/consultas.xml", "utf8");
var json = "";
parser.parseString(xml_string, function (error, result) {
  if (error === null) {
fork icon0
star icon0
watch icon1

3
4
5
6
7
8
9
10
11
12
13
const { once } = require('events');
const compare = require("../common/compare");
const rand_file = require('../common/rand_file');
var archiver = require('archiver');
var xml2json = require('xml2js');
var parser = new xml2json.Parser();


// Save the submitted code to a local file and save the submission information into the database
exports.submit_answer = async function (req, res) {
    console.log(req.headers);
fork icon0
star icon0
watch icon1

170
171
172
173
174
175
176
177
178
}
var command = commandQueue.shift();

var validateNumber = command.serialNumber.toString();

var parser = new xml2js.Parser();
parser.parseString(dictXML[command.selectedCommand], function (err, result) {

    if (command.selectedCommand == "Transmitir Perfil" || command.selectedCommand == "Inibir Apagar FPs" || command.selectedCommand == "Envia Configuracao FP" || command.selectedCommand == "LiberarFPs") {
fork icon0
star icon0
watch icon1

+ 11 other calls in file

10
11
12
13
14
15
16
17
18
19
20
21
22
23


// const carsLinks = [ "https://export.maxposter.ru/tradedealer/4579-45794.xml"] //ссылка на файлы от Макспостера
const axios = require('axios').default


const db = new PrismaClient()
const parser = new xml2js.Parser()




async function start() {
    try {
fork icon0
star icon0
watch icon1

+ 9 other calls in file

5
6
7
8
9
10
11
12
13
14
15
16
const io = require("./socket-io")();
const LogType = require("../models/logStructure/logType");
const PresentationActions = require("./../models/opensong/PresentationActions");
const PresentationSlideTypes = require("./../models/opensong/PresentationSlideTypes");


var parser = new xml2js.Parser({
    preserveWhitespace: true
});


var client = new WebSocketClient();
fork icon0
star icon0
watch icon1

+ 5 other calls in file

4
5
6
7
8
9
10
11
12
13
14
15
const Database = require('@replit/database');


const app = express();
const lastAlarmEndpoint = process.env['LAST_ALARM_ENDPOINT'];
const maxSavedAlarms = 50;
const parser = new xml2js.Parser({ explicitArray: false });
const db = new Database();


function getLastAlarm(portalID) {
	const url = `${lastAlarmEndpoint}?portalID=${portalID}`;
fork icon0
star icon0
watch icon1