Last active
May 22, 2024 06:22
-
-
Save Aravin/19819311a863f7342e81e069102ea19d to your computer and use it in GitHub Desktop.
Converting JSON toXML& XML to JSON in Node.js using xml2js package in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { parseString, Builder } from "xml2js"; | |
// Convert string/XML to JSON | |
function toJson(xml: string) { | |
parseString(xml, { explicitArray: false }, function(error, result) { | |
console.log(result); | |
}); | |
} | |
// Convert string/JSON to XML | |
function toXML(json: string) { | |
const builder = new Builder(); | |
console.log(builder.buildObject(json)); | |
} | |
// Test Data | |
const employeeJson: any = { | |
Employee: { | |
name: 'Aravind', | |
age: 24, | |
sex: 'Male' | |
} | |
}; | |
const employeeXml = "<Employee><name>Aravind</name><age>24</age><sex>Male</sex></Employee>" | |
// Result | |
toJson(employeeXml); | |
toXML(employeeJson); | |
//// | |
/// SAMPLE OUTPUT | |
//// | |
{ Employee: { name: 'Aravind', age: '24', sex: 'Male' } } | |
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> | |
<Employee> | |
<name>Aravind</name> | |
<age>24</age> | |
<sex>Male</sex> | |
</Employee> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment