Node - Load an Xml File with xmldom
- Estimated read time: 3 min read
- Written by Chad Campbell on Aug 26th 2013
Often times you'll find yourself needing to load a serialized version of some data. Sometimes that data may be represented as XML. In those cases where you're working in a Node environment, you can use the xmldom package.
Once installed, you can parse an XML file with the following code:
The above snippet works as follows:
- Line 1 - The Node.js File System module provides wrappers to work with File I/O. We need these wrappers to access the .xml file on the local file system.
- Line 2 - The DOMParser from the xmldom 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 7 - This is where the contents of the file are loaded as XML.
This small bit of code empowers you to open XML files in Node. In the event that the XML is invalid, you will receive an error that says something like "end tag name: teams is not match the current start tagName:undefined". You will also receive this error if the contents of your XML file do not include the XML declaration mentioned here.
It is also important to note that as of Node v0.10.17 and xmldom 0.1.16, this example will only work if the xmldom package is installed locally. A global installation of xmldom will not work. If the package is not installed locally, you will receive an error that says something to the tune of "Error: Cannot find module 'xmldom'".
With the notes above, you should be able to successfully open an .xml file in Node. 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.