Home  >  Article  >  Web Front-end  >  How to format and highlight xml string in js? (with code)

How to format and highlight xml string in js? (with code)

不言
不言Original
2018-08-13 10:07:422879browse

本篇文章给大家带来的内容是关于js如何格式化xml字符串并高亮?(附代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

两个关键点

  1. 使用DOMParser解析xml

  2. 递归遍历xml树,按格式输出每一个节点

关于使用DOMParser

此方法目前在IE9以上和其它浏览器里都是支持的,所以这里不在写关于IE9以下不支持的情况。

Javascript代码

/**
 * 格式化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(&#39;    &#39;);
        }
        t = t.join("");
        list.push(t + &#39;&lt;<span class="code-key">&#39;+ element.nodeName +&#39;</span>&gt;\n&#39;);
        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)) ? &#39;code-number&#39; : &#39;code-string&#39;;
                let value_txt = &#39;<span class="&#39;+ value_color +&#39;">&#39; + value + &#39;</span>&#39;;
                let item = t + &#39;    &lt;<span class="code-key">&#39; + nodeName +
                    &#39;</span>&gt;&#39; + value_txt + &#39;&lt;/<span class="code-key">&#39; + nodeName + &#39;</span>&gt;\n&#39;;
                list.push(item);
            } else {
                build_xml(++index, list, element.childNodes[i]);
            }
        }
        list.push(t + &#39;&lt;/<span class="code-key">&#39;+ element.nodeName +&#39;</span>&gt;\n&#39;);
    }

    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;}

效果

How to format and highlight xml string in js? (with code)

注意

DOMParser在解析xml时,如果xml字符串里有些特殊的字符,解出来的树节点有些是不需要的,会倒置遍历节点失败。

最后

这些方法已用于YuiAPI

相关推荐:

js的继承方式有哪些?js实现继承的几种方式介绍

js执行机制的概念?js的执行机制的实现方法

The above is the detailed content of How to format and highlight xml string in js? (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn