Node - Load an Xml File with Xml2Js
- Written by Chad Campbell on Aug 31st 2013
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.
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
- Line 9 - Parses the XML loaded from the
filePathset 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
resultobject with a call to
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.