Node - Load an Xml File with Xml2Js

Sometimes you need to load a serialized version of some data. On some occassions that data may be represented as XML. In those cases where you're working in a Node environment, you can use the XML2JS package.

The XML2JS packge empowers you to convert XML to JavaScript. To install this module, you can use Node's package manager and install the latest version using the following command:

npm install xml2js

Once installed, you can load an XML file and convert its contents to JSON using the following code: The above snippet works as follows:
  • Line 1 - The Node.js File System module provides wrappers to work with the file system. We need these wrappers to access the .xml file on the local file system.
  • Line 2 - The xml2js module is loaded and aliased for later use in line 7.
  • Line 6 - The contents of the .xml file is read from the file system synchronously. In this example, we are specifying that ASCII encoding should be used.
  • Line 8 - A new instance of the XML2JS parser is created. You should only create on XML2JS parser per file based on the contents of the documentation. If you're worried about it being in a stale state, you can call its reset() function.
  • Line 9 - Parses the XML loaded from the filePath set in Line 4.
  • Line 10 - Assuming the XML was successfully parsed in line 9, we can convert the file contents into JSON by wrapping the result object with a call to JSON.stringify
This code sampling will let you open an XML file and convert its contents to JSON in Node. In the event that the XML is invalid, the err object shown in line 9 will be something other than null. The exact information will vary based on why the XML is invalid.

With the notes above, you should be able to successfully open an .xml file and convert its contents to JSON in Node. If you found this post valuable, please consider +1-ing, like-ing, share-ing, etc below. If you have any questions or comments related to this post, please leave them in the comments below. If you would like other help from Ecofic, please Contact Us.