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
- 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
errobject shown in line 9 will be something other than
null. The exact information will vary based on why the XML is invalid.