JSFiddle - React, Tailwind, and code Playground
HTML
<html>
<body>
<div id="xmldata"></div>
</body>
</html>
CSS
.xtb { display: table; font-family: monospace; }
.xtc { display: table-cell; }
.xmt { color: #0000CC; display: inline; }
.xel { color: #990000; display: inline; }
.xdt { color: #000000; display: inline; }
.xat { color: #FF0000; display: inline; }
JavaScript
function formatXml(xml,colorize,indent) {
function esc(s){return s.replace(/[-\/&<> ]/g,function(c){ // Escape special chars
return c==' '?' ':'&#'+c.charCodeAt(0)+';';});}
var sm='<div class="xmt">',se='<div class="xel">',sd='<div class="xdt">',
sa='<div class="xat">',tb='<div class="xtb">',tc='<div class="xtc">',
ind=indent||' ',sz='</div>',tz='</div>',re='',is='',ib,ob,at,i;
if (!colorize) sm=se=sd=sa=sz='';
xml.match(/(?<=<).*(?=>)|$/s)[0].split(/>\s*</).forEach(function(nd){
ob=('<'+nd+'>').match(/^(<[!?\/]?)(.*?)([?\/]?>)$/s); // Split outer brackets
ib=ob[2].match(/^(.*?)>(.*)<\/(.*)$/s)||['',ob[2],'']; // Split inner brackets
at=ib[1].match(/^--.*--$|=|('|").*?\1|[^\t\n\f \/>"'=]+/g)||['']; // Split attributes
if (ob[1]=='</') is=is.substring(ind.length); // Decrease indent
re+=tb+tc+esc(is)+tz+tc+sm+esc(ob[1])+sz+se+esc(at[0])+sz;
for (i=1;i<at.length;i++) re+=(at[i]=="="?sm+"="+sz+sd+esc(at[++i]):sa+' '+at[i])+sz;
re+=ib[2]?sm+esc('>')+sz+sd+esc(ib[2])+sz+sm+esc('</')+sz+se+ib[3]+sz:'';
re+=sm+esc(ob[3])+sz+tz+tz;
if (ob[1]+ob[3]+ib[2]=='<>') is+=ind; // Increase indent
});
return re;
}
xmlstring =
xmlstring =
'<?xml version="1.0" encoding="UTF-8"?>' +
'<SoftwareEngineer>' +
'<empl id="01">' +
'<name>' +
'<projectname> Man-router</projectname>' +
'<Workingdomain> machine learning</Workingdomain>' +
'</name>' +
'<Enddate>' +
'<entities><![CDATA[ ' +
'This is the local project with the fibre optics.' +
'All the statistical manipulation is performed. Example. & and submission date 12/12/2020' +
']]></entities>' +
'</Enddate>' +
'</empl>' +
'</SoftwareEngineer>';
xmldiv = document.getElementById('xmldata');
xmldiv.innerHTML = formatXml(xmlstring,true);