'Convert JSON to XML with attributes in Javascript

I need to convert the JSON to XML with some properties as attributes.

For example:

JSON

{
      "Student":{
           "@Studentname":"Ravi",
           "@age":21,
           "college":"Anna University"
       }
}

Desired Output XML

<Student name="Ravi" age=21>
  <college>Anna University</college>
</Student>


Solution 1:[1]

Try the x2js library.

The default attribute prefix is "_" but can be overridden by using the attributePrefix config setting.

const X2JS = window.X2JS;  // node: require('x2js')


const x2js = new X2JS({ attributePrefix:"@" })

const jsonObj = {"Student":{"@Studentname":"Ravi","@age":21,"college":"Anna University"}}

const xmlString = x2js.js2xml(jsonObj)

console.log(xmlString)
<script src="https://unpkg.com/[email protected]/x2js.js"></script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Justin Ohms