Try it yourself with our free Xml Formatter tool — runs entirely in your browser, no signup needed.

How to Convert XML to JSON in Node.js

How to Convert XML to JSON in Node.js

Converting XML to JSON is a common task in web development, especially when working with APIs that return data in XML format. Node.js provides several libraries to achieve this, but in this guide, we'll focus on using the popular xml2js library. We'll explore a quick example, step-by-step breakdown, handling edge cases, common mistakes, performance tips, and frequently asked questions.

Installation

Before we dive into the code, make sure to install the required library by running the following command in your terminal:

npm install xml2js

Quick Example

Here's a minimal example that converts a simple XML string to JSON:

const xml2js = require('xml2js');

const xml = `
  <root>
    <person>
      <name>John Doe</name>
      <age>30</age>
    </person>
  </root>
`;

xml2js.parseString(xml, (err, result) => {
  if (err) {
    console.error(err);
  } else {
    console.log(JSON.stringify(result, null, 2));
  }
});

This code will output the following JSON:

{
  "root": {
    "person": {
      "name": "John Doe",
      "age": "30"
    }
  }
}

Step-by-Step Breakdown

Let's walk through the code line by line:

  1. const xml2js = require('xml2js');: We import the xml2js library using the require function.
  2. const xml = '...': We define a sample XML string.
  3. xml2js.parseString(xml, (err, result) => {...}): We call the parseString method, passing the XML string as the first argument and a callback function as the second argument.
  4. if (err) {...}: We check if an error occurred during parsing. If so, we log the error to the console.
  5. console.log(JSON.stringify(result, null, 2)): If no error occurred, we log the resulting JSON object to the console, pretty-printed with two spaces of indentation.

Handling Edge Cases

Here are a few common edge cases to consider:

Empty/Null Input

What happens if we pass an empty string or null to the parseString method?

xml2js.parseString('', (err, result) => {
  console.log(err); // Output: Error: Invalid XML: ''
});

xml2js.parseString(null, (err, result) => {
  console.log(err); // Output: Error: Invalid XML: null
});

In both cases, the library throws an error.

Invalid Input

What if the input XML is invalid?

const invalidXml = '<root></person>';

xml2js.parseString(invalidXml, (err, result) => {
  console.log(err); // Output: Error: Invalid XML: <root></person>
});

Again, the library throws an error.

Large Input

What if the input XML is very large?

const largeXml = Array(1000).fill('<person><name>John Doe</name><age>30</age></person>').join('');

xml2js.parseString(largeXml, (err, result) => {
  console.log(result); // Output: a large JSON object
});

The library can handle large inputs, but be aware that parsing large XML files can be memory-intensive.

Unicode/Special Characters

What if the input XML contains Unicode or special characters?

const xmlWithUnicode = `
  <root>
    <person>
      <name>John Dœ</name>
      <age>30</age>
    </person>
  </root>
`;

xml2js.parseString(xmlWithUnicode, (err, result) => {
  console.log(result); // Output: a JSON object with Unicode characters
});

The library can handle Unicode and special characters correctly.

Common Mistakes

Here are a few common mistakes developers make when using xml2js:

Mistake 1: Not handling errors

xml2js.parseString(xml, (err, result) => {
  console.log(result); // Don't do this!
});

Corrected code:

xml2js.parseString(xml, (err, result) => {
  if (err) {
    console.error(err);
  } else {
    console.log(result);
  }
});

Mistake 2: Not using the async version

const result = xml2js.parseStringSync(xml);

Corrected code:

xml2js.parseString(xml, (err, result) => {
  // Handle result here
});

Mistake 3: Not checking for null results

const result = xml2js.parseStringSync(xml);
console.log(result.root); // Don't do this!

Corrected code:

xml2js.parseString(xml, (err, result) => {
  if (result && result.root) {
    console.log(result.root);
  }
});

Performance Tips

Here are a few performance tips for using xml2js:

  1. Use the async version: The async version of parseString is more efficient than the synchronous version.
  2. Use a streaming parser: If you're working with very large XML files, consider using a streaming parser like xml-stream.
  3. Avoid unnecessary parsing: Only parse the XML data that you need to process.

FAQ

Q: What is the difference between xml2js and fast-xml-parser?

A: xml2js is a more mature library with better support for edge cases, while fast-xml-parser is a faster library with better performance.

Q: Can I use xml2js with other libraries like express or koa?

A: Yes, xml2js can be used with other libraries like express or koa to handle XML requests and responses.

Q: How do I handle XML namespaces?

A: You can handle XML namespaces by using the xmlns attribute in your XML data and the namespace option in the parseString method.

Q: Can I use xml2js with TypeScript?

A: Yes, xml2js has TypeScript definitions and can be used with TypeScript projects.

Q: What is the maximum size limit for XML input?

A: There is no maximum size limit for XML input, but parsing very large XML files can be memory-intensive.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp