Javascript formatting and highlighting xml strings
Two key points
- Parsing xml with DOMParser
- Recursively traverses the xml tree and outputs each node in a format
About using DOMParser
This method is currently supported in IE9 and other browsers, so we are not writing about the situation that is not supported in IE9 or below. Please skip to for specific use
https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
Javascript code
/** * Formatting xml * @param content * @returns {*} */ this.parse_xml = function(content) { let xml_doc = null; try { xml_doc = (new DOMParser()).parseFromString(content.replace(/[\n\r]/g, ""), 'text/xml'); } catch (e) { return false; } function build_xml(index, list, element) { let t = []; for (let i = 0; i < index; i++) { t.push(' '); } t = t.join(""); list.push(t + '<<span class="code-key">'+ element.nodeName +'</span>>\n'); for (let i = 0; i < element.childNodes.length; i++) { let nodeName = element.childNodes[i].nodeName; if (element.childNodes[i].childNodes.length === 1) { let value = element.childNodes[i].childNodes[0].nodeValue; let value_color = !isNaN(Number(value)) ? 'code-number' : 'code-string'; let value_txt = '<span class="'+ value_color +'">' + value + '</span>'; let item = t + ' <<span class="code-key">' + nodeName + '</span>>' + value_txt + '</<span class="code-key">' + nodeName + '</span>>\n'; list.push(item); } else { build_xml(++index, list, element.childNodes[i]); } } list.push(t + '</<span class="code-key">'+ element.nodeName +'</span>>\n'); } let list = []; build_xml(0, list, xml_doc.documentElement); return list.join(""); };
css
.code-string{color:#993300;} .code-number{color:#cc00cc;} .code-boolean{color:#000033;} .code-null{color:magenta;} .code-key{color:#003377;font-weight:bold;}
Effect
Be careful
When DOMParser parses xml, if there are some special characters in the xml string and some tree nodes are unnecessary, it will fail to traverse the nodes upside down.
Last
Some methods have been used in YuiAPI