Format XML in the Browser (DOMParser)

The browser's built-in DOMParser parses XML strings into a DOM document. A simple recursive function can then serialize it with indentation.

function formatXML(xml, indent = '  ') {
  const parser = new DOMParser();
  const doc = parser.parseFromString(xml, 'application/xml');

  function serializeNode(node, level) {
    const pad = indent.repeat(level);
    if (node.nodeType === Node.TEXT_NODE) {
      const text = node.textContent.trim();
      return text ? pad + text : '';
    }
    if (node.nodeType === Node.ELEMENT_NODE) {
      const tag = node.tagName;
      const attrs = Array.from(node.attributes)
        .map(a => ` ${a.name}="${a.value}"`)
        .join('');
      const children = Array.from(node.childNodes)
        .map(c => serializeNode(c, level + 1))
        .filter(Boolean);
      if (children.length === 0) return `${pad}<${tag}${attrs}/>`;
      if (children.length === 1 && !children[0].includes('\n')) {
        return `${pad}<${tag}${attrs}>${children[0].trim()}</${tag}>`;
      }
      return `${pad}<${tag}${attrs}>\n${children.join('\n')}\n${pad}</${tag}>`;
    }
    return '';
  }

  return serializeNode(doc.documentElement, 0);
}

console.log(formatXML('<root><name>Alice</name><age>30</age></root>'));

Format XML in Node.js (regex-based, no library)

function formatXML(xml, indent = '  ') {
  let result = '';
  let level = 0;
  xml.replace(/>\s*</g, '>\n<')
     .split('\n')
     .forEach(line => {
       line = line.trim();
       if (!line) return;
       if (line.startsWith('</')) level--;
       result += indent.repeat(Math.max(0, level)) + line + '\n';
       if (line.startsWith('<') && !line.startsWith('</') &&
           !line.endsWith('/>') && !line.includes('</')) level++;
     });
  return result.trim();
}

const xml = '<root><name>Alice</name><age>30</age></root>';
console.log(formatXML(xml));

Format XML with xml-formatter (npm)

// npm install xml-formatter
import xmlFormat from 'xml-formatter';

const xml = '<root><name>Alice</name><age>30</age></root>';
const formatted = xmlFormat(xml, {
  indentation: '  ',
  collapseContent: true
});
console.log(formatted);

Need to format XML without writing code?

Paste any XML into the free online formatter — instant results, no setup needed.

Open XML Formatter →

Frequently Asked Questions

How do I pretty print XML in JavaScript?

In the browser, use DOMParser to parse and a recursive serialize function to indent. In Node.js, use the xml-formatter npm package for the simplest solution.

Can I format XML without a library in Node.js?

Yes — the regex-based approach above works for most standard XML. It splits on tag boundaries and tracks indentation level. For complex XML with namespaces or mixed content, use a proper parser.

What is the best npm package for XML formatting?

xml-formatter is lightweight and widely used. fast-xml-parser is faster for large documents. For full XML processing, libxmljs2 has the most features.