You can use the async / await pattern to do this, for example:
const parseString = require('xml2js').parseString;
const xmlInput = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetCurrentRoomStatusGraphResponse xmlns="www.example.com"><GetCurrentRoomStatusGraphResult><RoomStatusGraphItem><RoomID>3</RoomID><ChainID>1</ChainID><RoomNo>8888</RoomNo><RoomTypeID>1</RoomTypeID><RoomTypeCode>DF</RoomTypeCode><RoomTypeName>standard room</RoomTypeName><RoomRate>0.0000</RoomRate><Floor>2</Floor><FolioID>123456</FolioID><Guest><RoomStatusGuest><Name>Jon Snow</Name><Sex>1</Sex><VipTypeID>0</VipTypeID></RoomStatusGuest></Guest><Arrival>2019-03-07T13:43:00</Arrival><Depart>2019-03-08T12:00:00</Depart><IsDepart>false</IsDepart><IsTimeRoom>false</IsTimeRoom><Surreptitious>false</Surreptitious><CheckInState>CheckIn</CheckInState><ClentState>NoClean</ClentState><HouseKeepState>EnableSaleRoom</HouseKeepState><CheckRoomFlag>false</CheckRoomFlag><IsBookInRoom>false</IsBookInRoom><IsFreeRoom>false</IsFreeRoom><IsInnerRoom>true</IsInnerRoom><IsThirdOTA>false</IsThirdOTA><IsAssociationRoom>false</IsAssociationRoom><RoomRemark /><FolioInnerRemark /><FolioRemark /><AddtionalFlag><int>1</int></AddtionalFlag><IsReserve>false</IsReserve><ClearRoomType>3</ClearRoomType><ClearRoomTypeName>normal</ClearRoomTypeName><CheckOutID>0</CheckOutID><CheckOutState>None</CheckOutState><MilkMarketStatus>0</MilkMarketStatus></RoomStatusGraphItem></GetCurrentRoomStatusGraphResult></GetCurrentRoomStatusGraphResponse></soap:Body></soap:Envelope>';
function parseXml(xml) {
return new Promise((resolve, reject) => {
parseString(xml, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
}
function processResult(result) {
console.log("processResult: result: ", result);
}
async function testXmlParse(xml) {
try {
let result = await parseXml(xml);
// Now that you have the result you can do further processing, write to file etc.
processResult(result);
} catch (err) {
console.error("parseXml failed: ", err);
}
}
testXmlParse(xmlInput);
Answer from Terry Lennox on Stack Overflownpm
npmjs.com › package › xml2js
xml2js - npm
Can't get easier than this, right? This works starting with xml2js 0.2.3. With CoffeeScript it looks like this: {parseString} = require 'xml2js' xml = "<root>Hello xml2js!</root>" parseString xml, (err, result) -> console.dir result
» npm install xml2js
Published Jul 26, 2023
Version 0.6.2
Author Marek Kubica
Top answer 1 of 2
3
You can use the async / await pattern to do this, for example:
const parseString = require('xml2js').parseString;
const xmlInput = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetCurrentRoomStatusGraphResponse xmlns="www.example.com"><GetCurrentRoomStatusGraphResult><RoomStatusGraphItem><RoomID>3</RoomID><ChainID>1</ChainID><RoomNo>8888</RoomNo><RoomTypeID>1</RoomTypeID><RoomTypeCode>DF</RoomTypeCode><RoomTypeName>standard room</RoomTypeName><RoomRate>0.0000</RoomRate><Floor>2</Floor><FolioID>123456</FolioID><Guest><RoomStatusGuest><Name>Jon Snow</Name><Sex>1</Sex><VipTypeID>0</VipTypeID></RoomStatusGuest></Guest><Arrival>2019-03-07T13:43:00</Arrival><Depart>2019-03-08T12:00:00</Depart><IsDepart>false</IsDepart><IsTimeRoom>false</IsTimeRoom><Surreptitious>false</Surreptitious><CheckInState>CheckIn</CheckInState><ClentState>NoClean</ClentState><HouseKeepState>EnableSaleRoom</HouseKeepState><CheckRoomFlag>false</CheckRoomFlag><IsBookInRoom>false</IsBookInRoom><IsFreeRoom>false</IsFreeRoom><IsInnerRoom>true</IsInnerRoom><IsThirdOTA>false</IsThirdOTA><IsAssociationRoom>false</IsAssociationRoom><RoomRemark /><FolioInnerRemark /><FolioRemark /><AddtionalFlag><int>1</int></AddtionalFlag><IsReserve>false</IsReserve><ClearRoomType>3</ClearRoomType><ClearRoomTypeName>normal</ClearRoomTypeName><CheckOutID>0</CheckOutID><CheckOutState>None</CheckOutState><MilkMarketStatus>0</MilkMarketStatus></RoomStatusGraphItem></GetCurrentRoomStatusGraphResult></GetCurrentRoomStatusGraphResponse></soap:Body></soap:Envelope>';
function parseXml(xml) {
return new Promise((resolve, reject) => {
parseString(xml, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
}
function processResult(result) {
console.log("processResult: result: ", result);
}
async function testXmlParse(xml) {
try {
let result = await parseXml(xml);
// Now that you have the result you can do further processing, write to file etc.
processResult(result);
} catch (err) {
console.error("parseXml failed: ", err);
}
}
testXmlParse(xmlInput);
2 of 2
2
you can use the short method
import { parseStringPromise } from 'xml2js';
xmlresponse = `<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Header>
<QAInformation
xmlns="http://www.qas.com/OnDemand-2011-03">
<StateTransition>SearchResults</StateTransition>
<CreditsUsed>1</CreditsUsed>
</QAInformation>
</soap:Header>
<soap:Body>
<Address
xmlns="http://www.qas.com/OnDemand-2011-03">
<QAAddress DPVStatus="DPVNotConfigured">
<AddressLine LineContent="None">
<Label />
<Line>Commonwealth Bank Building</Line>
</AddressLine>
<AddressLine LineContent="None">
<Label />
<Line>L 10 71-89 Adelaide St</Line>
</AddressLine>
<AddressLine LineContent="None">
<Label />
<Line />
</AddressLine>
<AddressLine>
<Label>Locality</Label>
<Line>BRISBANE CITY</Line>
</AddressLine>
<AddressLine>
<Label>State code</Label>
<Line>QLD</Line>
</AddressLine>
<AddressLine>
<Label>Postcode</Label>
<Line>4000</Line>
</AddressLine>
<AddressLine>
<Label>Country</Label>
<Line>AUSTRALIA</Line>
</AddressLine>
<AddressLine LineContent="Ancillary">
<Label>DPID/DID</Label>
<Line>87902264</Line>
</AddressLine>
</QAAddress>
</Address>
</soap:Body>
</soap:Envelope>`
let convert = await parseStringPromise(xmlresponse);
convert = (JSON.parse(JSON.stringify(convert)));
console.log(convert['soap:Envelope']['soap:Body'][0]['Address'][0]['QAAddress'][0]['AddressLine']);
you will have something like this
[
{
'$': { LineContent: 'None' },
Label: [ '' ],
Line: [ 'Commonwealth Bank Building' ]
},
{
'$': { LineContent: 'None' },
Label: [ '' ],
Line: [ 'L 10 71-89 Adelaide St' ]
},
{ '$': { LineContent: 'None' }, Label: [ '' ], Line: [ '' ] },
{ Label: [ 'Locality' ], Line: [ 'BRISBANE CITY' ] },
{ Label: [ 'State code' ], Line: [ 'QLD' ] },
{ Label: [ 'Postcode' ], Line: [ '4000' ] },
{ Label: [ 'Country' ], Line: [ 'AUSTRALIA' ] },
{
'$': { LineContent: 'Ancillary' },
Label: [ 'DPID/DID' ],
Line: [ '87902264' ]
}
]
Snyk
snyk.io › advisor › xml2js › functions › xml2js.parsestring
How to use the xml2js.parseString function in xml2js | Snyk
request.get(location.href, function(err, res, xml) { if (!err) { xml2js.parseString(xml, function(err, json) { if (!err && json && json.root) { var device = { ip: location.hostname, port: location.port }; for (var key in json.root.device[0]) { device[key] = json.root.device[0][key][0]; } if (device.deviceType == "urn:Belkin:device:bridge:1") { //console.log( device.ip + ' -' + device.deviceType); var ip = device.ip; var port = device.port; var udn = device.UDN; var postoptions = { host: ip, port: port, path: getenddevs.path, method: 'POST', headers: {
GitHub
github.com › Leonidas-from-XIV › node-xml2js
GitHub - Leonidas-from-XIV/node-xml2js: XML to JavaScript object converter. · GitHub
Can't get easier than this, right? This works starting with xml2js 0.2.3. With CoffeeScript it looks like this: {parseString} = require 'xml2js' xml = "<root>Hello xml2js!</root>" parseString xml, (err, result) -> console.dir result
Starred by 5K users
Forked by 612 users
Languages CoffeeScript
GitHub
github.com › vavere › xml2js-parser
GitHub - vavere/xml2js-parser: Simple XML to JavaScript object converter
You want to parse XML as simple and easy as possible? Take this: const parseString = require('xml2js-parser').parseString; const xml = '<root>Hello xml2js-parser!</root>'; parseString(xml, (err, result) => { console.dir(result); });
Author vavere
Snyk
snyk.io › advisor › xml2js › xml2js code examples
Top 5 xml2js Code Examples | Snyk
April 6, 2023 - 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
CloudDefense.ai
clouddefense.ai › code › javascript › example › xml2js
Top 10 Examples of xml2js code in Javascript
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
Npmdoc
npmdoc.github.io › node-npmdoc-xml2js › build › apidoc.html
api documentation for xml2js (v0.4.17)
parseString = function (str, a, b) { var cb, options, parser; if (b != null) { if (typeof b === 'function') { cb = b; } if (typeof a === 'object') { options = a; } } else { if (typeof a === 'function') { cb = a; } options = {}; } parser = new exports.Parser(options); return parser.parseString(str, cb); } ... ... ```javascript var fs = require('fs'), xml2js = require('xml2js'); var parser = new xml2js.Parser(); fs.readFile(__dirname + '/foo.xml', function(err, data) { parser.parseString(data, function (err, result) { console.dir(result); console.log('Done'); }); }); ``` Look ma, no event listeners!
UNPKG
unpkg.com › browse › xml2js@0.4.0 › README.md
xml2js
This works starting with `xml2js` ... this: ```coffeescript {parseString} = require 'xml2js' xml = "<root>Hello xml2js!</root>" parseString xml, (err, result) -> console.dir result ``` If you need some special options, fear not, `xml2js` supports a number of options (see below), you can specify these as second argument: ```javascript parseString(xml, {trim: true}, function (err, result) { }); ``` Simple ...
Tabnine
tabnine.com › home page › code › javascript › parser
xml2js.Parser.parseString JavaScript and Node.js code examples | Tabnine
// XML 对象转 JSON 对象 var xml2json = function (bodyStr) { var d = {}; xmlParser.parseString(bodyStr, function (err, result) { d = result; }); return d; }
Tabnine
tabnine.com › home page › code › javascript › xml2js
xml2js.Parser JavaScript and Node.js code examples | Tabnine
program.arguments('<file>').action(function (file) { var xmlParser = new xml2js.Parser(); function setupDict() { return new Promise(function (resolve, reject) { fs.readFile(file, function (err, rawData) { if (err) { log(err); process.exit(1); } var data = escape(rawData.toString(), XML_IGNORE); xmlParser.parseString(data, function (parseError, obj) { if (parseError) reject(parseError);else resolve(obj.JMdict.entry); }); }); }); } var outputFilename = "".concat(file, ".json"); setupDict().then(function (dictionary) { fs.writeFileSync(outputFilename, JSON.stringify(dictionary), 'utf8'); }); }); origin: DinoChiesa/apigee-edge-js ·
Examplejavascript
examplejavascript.com › xml2js › parsestring
How to use the parseString function from xml2js
248 249 250 251 252 253 254 255 256 257 }; async.waterfall([ next => bucketPut(authInfo, testPutBucketRequest, log, next), (corsHeaders, next) => initiateMultipartUpload(authInfo, initiateRequest, log, next), (result, corsHeaders, next) => parseString(result, next), (json, next) => { const testUploadId = json.InitiateMultipartUploadResult.UploadId[0]; const md5Hash = crypto.createHash('md5').update(partBody); ... 668 669 670 671 672 673 674 675 676 677 } else { var content_type = response.headers['content-type']; var response_text = name + " N/A"; if (content_type == 'application/xml;charset=UTF-8') { xml2js.parseString(body, { tagNameProcessors: [settingsApi.stripPrefix], attrNameProcessors: [settingsApi.stripPrefix] }, function(err, result) { if (err) {
npm
npmjs.com › package › xml2js-parser
xml2js-parser - npm
November 16, 2016 - Yo install just type npm install xml2js-parser which will download xml2js-parser and dependencies. You want to parse XML as simple and easy as possible? Take this: const parseString = require('xml2js-parser').parseString;
» npm install xml2js-parser
Published Nov 16, 2016
Version 1.1.1
Author Lauris Vavere
Repository https://github.com/vavere/xml2js-parser
UNPKG
unpkg.com › browse › xml2js@0.2.3 › README.md
xml2js/README.md
This works starting with `xml2js` 0.2.3. With CoffeeScript it looks like this: ```coffeescript parseString = require('xml2js').parseString; xml = "<root>Hello xml2js!</root>" parseString xml, (err, result) -> console.dir result ``` If you need some special options, fear not, `xml2js` supports ...
Readthedocs
rgi-assessment-tool.readthedocs.io › en › stable › node_modules › s3 › node_modules › aws-sdk › node_modules › xml2js › README.html
node-xml2js — rgi-assessment-tool stable documentation
Can’t get easier than this, right? This works starting with xml2js 0.2.3. With CoffeeScript it looks like this: parseString = require('xml2js').parseString xml = "<root>Hello xml2js!</root>" parseString xml, (err, result) -> console.dir result
IronPDF
ironpdf.com › ironpdf for node.js › ironpdf for node.js blog › node help › xml2js npm
xml2js npm (How It Works For Developers)
June 23, 2025 - Rowling</author> </book> <book category="nonfiction"> <title>Thinking, Fast and Slow</title> <author>Daniel Kahneman</author> </book> </bookstore> `; // Configure XML2JS parser with options const parser = new xml2js.Parser({ explicitArray: false, // Converts child elements to objects instead of arrays when there is only one child trim: true // Trims leading/trailing whitespace from text nodes }); // Parse XML content parser.parseString(xmlContent, (err, result) => { if (err) { console.error('Error parsing XML:', err); return; } console.log('Parsed XML to JavaScript object with options:', result); }); const xml2js = require('xml2js'); // Example XML content const xmlContent = ` <bookstore> <book category="fiction"> <title>Harry Potter</title> <author>J.K.
GitHub
github.com › Leonidas-from-XIV › node-xml2js › issues › 380
Why do we need a callback for parseString()? · Issue #380 · Leonidas-from-XIV/node-xml2js
April 28, 2017 - { var a; new require('xml2js').Parser().parseString(' asdf { a = r }); console.log(a); })(); and the output is: { xml: 'asdf' }
Author zszszsz