Converting an object to XML and back again
Since JSON is a string-based representation of a JavaScript object, converting between the two is straightforward. However, XML is less convenient to work with. Nevertheless, there may be times we have to work with it, for instance, if an API works only in XML or if we were contracted with a project that specifies XML support.
There are various non-core XML parsers available. One such parser is the non-core module xml2js
. The premise of xml2js
is that working with objects in JavaScript is more suitable than working with XML. xml2js
provides a basis for us to interact with XML by converting it to a JavaScript object.
In this task, we're going to write a function that uses our profiles
object featured in the previous recipe to create a valid XML string, which we'll then push through xml2js
, thus converting it back into an object.
Getting ready
Before we start, let's create our file xml_and_back.js
, making sure we have our separately modularized profiles...