Skip to content

Instantly share code, notes, and snippets.

@sente
Last active April 4, 2024 12:20
Show Gist options
  • Star 95 You must be signed in to star a gist
  • Fork 19 You must be signed in to fork a gist
  • Save sente/1083506 to your computer and use it in GitHub Desktop.
Save sente/1083506 to your computer and use it in GitHub Desktop.
javascript to format/pretty-print XML
function formatXml(xml) {
var formatted = '';
var reg = /(>)(<)(\/*)/g;
xml = xml.replace(reg, '$1\r\n$2$3');
var pad = 0;
jQuery.each(xml.split('\r\n'), function(index, node) {
var indent = 0;
if (node.match( /.+<\/\w[^>]*>$/ )) {
indent = 0;
} else if (node.match( /^<\/\w/ )) {
if (pad != 0) {
pad -= 1;
}
} else if (node.match( /^<\w[^>]*[^\/]>.*$/ )) {
indent = 1;
} else {
indent = 0;
}
var padding = '';
for (var i = 0; i < pad; i++) {
padding += ' ';
}
formatted += padding + node + '\r\n';
pad += indent;
});
return formatted;
}
xml_raw = '<foo><bar><baz>blahblah</baz><baz>tralala</baz></bar></foo>';
xml_formatted = formatXml(xml_raw);
xml_escaped = xml_formatted.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/ /g, '&nbsp;').replace(/\n/g,'<br />');
var mydiv = document.createElement('div');
mydiv.innerHTML = xml_escaped;
document.body.appendChild(mydiv);
@nleush
Copy link

nleush commented Feb 28, 2012

Google Search: javascript xml pretty print
I have it on last position of first page :)

@nikomaresco
Copy link

same here :) thanks, sente!

@TotallyInformation
Copy link

xml.replace -> should probably be xml.toString().replace(...)

Otherwise you get an error if you accidentally pass an object rather than a string.

@sente
Copy link
Author

sente commented Jan 24, 2014

@TotallyInformation - hmm, that's a good point!

@jasongoodwin
Copy link

xml pretty print javascript <- google search rank 3 today.

@renjuradhakrishnan
Copy link

Thanks a lot for sharing. Very helpful

@ubergoober
Copy link

xml pretty print javascript --- first position rank on google today. ;)

@kurtsson
Copy link

Thank you for a very useful piece of code. Here is my fork without the jQuery dependency (better for Node.js): https://gist.github.com/kurtsson/3f1c8efc0ccd549c9e31

@renjuradhakrishnan
Copy link

Just a note, xml formatting would fail, if there are whites paces between end and start tags of the input XML string. As a fix, replace var reg = /(>)(<)(/)/g; with var reg = /(>)\s(<)(/*)/g; in the script.

@ianbale
Copy link

ianbale commented Jun 2, 2015

I've just come across a small issue with CDATA sections. If these contain tags then this puts then on new lines introducing white space which can break the content of the CDATA section where white space may already be deliberately encoded.

eg. Here the CDATA section is protecting carriage returns contained in the string:

<!{CDATA[line 1
line 2
line 3
]]>

But after "pretty printing" it ends up as:

line 2 line 3 ]]>

which has changed the meaning of the text the CDATA section was enclosing.

Cool function in all other cases though! :-)

@mjswan
Copy link

mjswan commented Oct 30, 2015

Thank you. Works perfectly!

@Risord
Copy link

Risord commented Mar 18, 2016

node.match(/^<\w[^>][^\/]>.$/) seems not to match single letter elements like

@vishumertiya
Copy link

Thank u so much .. It helps a lot

@edemaine
Copy link

@Risord Indeed, that regular expression should be /^<\w([^>]*[^\/])?>.*$/

@sente
Copy link
Author

sente commented Dec 16, 2016

@edemaine, @Risord -- thank you. I've updated the regular expression.

@grubersjoe
Copy link

grubersjoe commented Nov 10, 2017

Thanks for the code.

Here's an adapted ES6 variant:

formatXml(xml) {
    const PADDING = ' '.repeat(2); // set desired indent size here
    const reg = /(>)(<)(\/*)/g;
    let pad = 0;

    xml = xml.replace(reg, '$1\r\n$2$3');

    return xml.split('\r\n').map((node, index) => {
        let indent = 0;
        if (node.match(/.+<\/\w[^>]*>$/)) {
            indent = 0;
        } else if (node.match(/^<\/\w/) && pad > 0) {
            pad -= 1;
        } else if (node.match(/^<\w[^>]*[^\/]>.*$/)) {
            indent = 1;
        } else {
            indent = 0;
        }

        pad += indent;

        return PADDING.repeat(pad - indent) + node;
    }).join('\r\n');
}

@theo-armour
Copy link

@grubersjoe

ES6 variant works for me. Thanks!

@nasermirzaei89
Copy link

nasermirzaei89 commented Mar 25, 2018

@grubersjoe
js lint fails with this message:

Unnecessary escape character: \/ no-useless-escape

so I used [^/] in last node.match function

@MagedSaeed
Copy link

MagedSaeed commented Apr 21, 2018

Many Thanks,, works perfect!!

@vsix27
Copy link

vsix27 commented Jun 11, 2018

did you try script on bad formed xml like

      <feed xmlns="http://www.w3.org/2005/Atom"
need="urgent">   <title type="general" sub="sample">Example Feed</title>
<subtitle><![CDATA[minor subtitle <<< ]]></subtitle>
<author nn="1" order="2" case="now"><name>John Doe</name><email>johndoe@example.com</email>
 </author>    <entry><title>Atom-Powered Robots Run Amok</title>
    <link href="http://example.org/2003/12/13/atom03" />
   <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
  <updated>2003-12-13T18:30:02Z</updated><summary>Some text.</summary>
 </entry>      </feed>

? it does not work for me

@JoaoPortella
Copy link

@grubersjoe
Many thanks!

@ezhov-da
Copy link

@ sente
Wow, so cool, thanks!

@huangwei16800
Copy link

<simple-value><![CDATA[部门

Dept]]>

after format xml, it will be follow result, have many space char before <![CDATA

@huangwei16800
Copy link

i had try, modify ,

var reg = /(>)(<)([^!])(/*)/g;

@brunolkatz
Copy link

thanks \o

@brennanyoung
Copy link

Good work - although I must point out that it doesn't touch existing whitespace indentation, with hilarious consequences.

@nishant-dutta
Copy link

Thanks for the code.

Here's an adapted ES6 variant:

formatXml(xml) {
    const PADDING = ' '.repeat(2); // set desired indent size here
    const reg = /(>)(<)(\/*)/g;
    let pad = 0;

    xml = xml.replace(reg, '$1\r\n$2$3');

    return xml.split('\r\n').map((node, index) => {
        let indent = 0;
        if (node.match(/.+<\/\w[^>]*>$/)) {
            indent = 0;
        } else if (node.match(/^<\/\w/) && pad > 0) {
            pad -= 1;
        } else if (node.match(/^<\w[^>]*[^\/]>.*$/)) {
            indent = 1;
        } else {
            indent = 0;
        }

        pad += indent;

        return PADDING.repeat(pad - indent) + node;
    }).join('\r\n');
}

Thanks for the ES6 version @grubersjoe ,a small addition though for handling newlines and existing whitespace between tags(as pointed out by @brennanyoung):

formatXml(xml) {
// Remove all the newlines and then remove all the spaces between tags
xml = xml.replace(/(\r\n|\n|\r)/gm, " ").replace(/>\s+</g,'><');

  const PADDING = ' '.repeat(4); // set desired indent size here
  const reg = /(>)(<)(\/*)/g;
  let pad = 0;

  xml = xml.replace(reg, '$1\r\n$2$3');

  return xml.split('\r\n').map((node, index) => {
      let indent = 0;
      if (node.match(/.+<\/\w[^>]*>$/)) {
          indent = 0;
      } else if (node.match(/^<\/\w/) && pad > 0) {
          pad -= 1;
      } else if (node.match(/^<\w[^>]*[^\/]>.*$/)) {
          indent = 1;
      } else {
          indent = 0;
      }

      pad += indent;

      return PADDING.repeat(pad - indent) + node;
  }).join('\r\n');

}

@ppazos
Copy link

ppazos commented Jul 27, 2020

I'm not sure if the latest versions of FF added more constraints, I'm getting "Toot much recursion" from formatXml()

@davidgolding
Copy link

davidgolding commented Nov 13, 2023

A slight mismatch in one of the regular expressions needs to be: node.match(/^<[\w^>]*[^\/]>.*$/)). Merging everyone's updates, here's what I've been using:

/**
 * Prettifies the tab indentation of given XML string
 *
 * @param xml string - The XML to clean
 * @return string - Prettified XML string
 */
static prettify(xml: String) {
    let pad = 0;
    const padding = '\u0020'.repeat(4); // set desired indent size here
    
    xml = xml.replace(/(\r\n|\n|\r)/gm, '\u0020').replace(/>\s+</g,'><');
    xml = xml.replace(/(>)(<)(\/*)/g, '$1\r\n$2$3');
    
    return xml.split('\r\n').map((node, index) => { //XML elements now split into lines
        let indent = 0;
        if (node.match(/.+<\/\w[^>]*>$/)) {
            indent = 0;
        } else if (node.match(/^<\/\w/) && pad > 0) {
            pad -= 1;
        } else if (node.match(/^<[\w^>]*[^\/]>.*$/)) {
            indent = 1;
        } else {
            indent = 0;
        }
        pad += indent;
        return padding.repeat(pad - indent) + node;
    }).join('\r\n');
}

@thetilliwilli
Copy link

jlyk: if (node.match(/.+<\/\w[^>]*>$/)) { - this is extremely slow on big rows.
not for production use for sure ;) - DannyDainton/newman-reporter-htmlextra#428 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment