logo

The next-generation blog, news, and article for you to start sharing your stories today!

NodeJs json to xml conversion

Node Js json to xml conversion.

Nodejs does not support internal xml to json convert functionality. To achieve this task we have a popular nodejs library that is ..

fast xml parser library.

Also we need a helper function to convert json to xml.

JSON to XML converter function.

See the below code to understand the conversion logic

const parser = require('fast-xml-parser');

class Helper {
	constructor() {
        
    }
    
	jsonToXml (json,config = null) {
        let options = {
            attributeNamePrefix : "@",
            textNodeName : "$",
            ignoreAttributes : false,
            tagValueProcessor: a=> he.encode(a.toString(), { useNamedReferences: false})
        };
        const jsparser = new parser.j2xParser(options);
        json = {xml:json};
        let xml = jsparser.parse(json);
        return '<?xml version="1.0" encoding="utf-8"?>' + xml;
    }
}

module.exports = new Helper();

Here is simple code for convert your json object in to the xml one.

JSON to XML converter function use.

Well below code of bunch is demostrate that how to use jsonToXml conversion function.

const Helper = require('../your-class-path/Helper')

const jsonObj = {
	"key" : 'your json obj'
};

let xmlString = Helper.jsonToXml(jsonObj);

 

So using this simple technique you can achive your goal.

Conclusion

Hello I am Vikram Parihar, So we have learnt how to write simple json to xml conversion code in  nodejs. Feel free to write comment and feedback.

avatar

Vikram Parihar

An editor at Keyscript

Vikram Parihar is an senior software engineer. He is working since 2013 in web development technologies. He works in NodeJS, Angular, Vue, PHP, Laravel, Express JS and various popular technologies.