Javascript formatting and highlighting xml strings

Keywords: Javascript xml

Javascript formatting and highlighting xml strings

Two key points

  1. Parsing xml with DOMParser
  2. 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('&nbsp;&nbsp;&nbsp;&nbsp;');
        }
        t = t.join("");
        list.push(t + '&lt;<span class="code-key">'+ element.nodeName +'</span>&gt;\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 + '&nbsp;&nbsp;&nbsp;&nbsp;&lt;<span class="code-key">' + nodeName +
                    '</span>&gt;' + value_txt + '&lt;/<span class="code-key">' + nodeName + '</span>&gt;\n';
                list.push(item);
            } else {
                build_xml(++index, list, element.childNodes[i]);
            }
        }
        list.push(t + '&lt;/<span class="code-key">'+ element.nodeName +'</span>&gt;\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

Posted by aznkidzx on Sat, 04 Jan 2020 20:57:08 -0800