js format xml and highlight keywords

Posted by bluegray on Tue, 03 Dec 2019 10:33:22 +0100

w3school XML DOM - DOMParser object

DOM parser parses XML tags to create a document.

Constructor

new DOMParser()

The domparser object parses the XML text and returns an XML Document object. To use DOMParser, instantiate it with a constructor without arguments, then call its parseFromString() method:

var doc = (new DOMParser()).parseFromString(text)

IE does not support DOMParser objects. Instead, it supports the use of Document.loadXML() XML parsing for.

DOMParser.parseFromString()

Parsing XML tags

grammar

parseFromString(text, contentType)

The text parameter is the XML tag to parse.

contentType is the content type of the text. It could be one of "text/xml", "application/xml" or "application/xhtml+xml". Note that "text/html" is not supported.

actual combat

  • js
   // Format xml highlight
  formatXml = function (content) {
    let xml_doc = null;
    const formatContent = content.replace(/[\n\r]/g, "");
    try {
      xml_doc = (new DOMParser()).parseFromString(formatContent, 'text/xml');
    } catch (e) {
      return false;
    }

    function build_xml(list, element, level) {
      let t = [];

      /*level Node level. How many spaces to indent before convenience*/
      for (let i = 0; i < level; 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++) {
        const childLevel = level + 1;
        let childItem = element.childNodes[i];
        let nodeName = childItem.nodeName;
        if (nodeName === '#text') {
          continue;
        }

        if (childItem.childNodes.length <= 1) {
          let value = '';
          if (childItem.childNodes.length === 1) {
            value = childItem.childNodes[0].nodeValue;
          }
          
          // Converting html tags to entities
          value = value ? value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;') : '';

          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 + '&lt;/<span class="code-key">' + nodeName + '</span>>\n';
          list.push(item);
        } else {
          build_xml(list, element.childNodes[i], childLevel);
        }
      }
      list.push(t + '&lt;/<span class="code-key">' + element.nodeName + '</span>>\n');
    }

    let list = [];
    build_xml(list, xml_doc.documentElement, 0);
    return list.join("");
  };
  • CSS style
  .code-string{color:green;}
  .code-number{color:darkorange;}
  .code-boolean{color:#000033;}
  .code-null{color:magenta;}
  .code-key{color:#003377;font-weight:bold;}
  • eg.

xml format

'<?xml version="1.0" encoding="UTF-8"?>↵<XhwNewsML><Version>0.0.1</Version><ApiType>article</ApiType><PushTime>2018-12-25 15:05:00</PushTime><ACTION>1</ACTION><Relevant/><NodeList>↵    <NodeInfo ID="11109319">↵      ↵      <GAttr>63</GAttr>↵      <GDisplayOrder>-66480150.1020580000000000000</GDisplayOrder>↵    <NodeId>11109319</NodeId></NodeInfo>↵    <NodeInfo ID="11187043">↵      ↵      <GAttr>63</GAttr>↵      <GDisplayOrder>-66480150.1020580000000000000</GDisplayOrder>↵    <NodeId>11187043</NodeId></NodeInfo>↵  </NodeList></XhwNewsML>'

Formatting effect

Topics: Javascript xml IE encoding