All files XmlBeautify.js

99.24% Statements 132/133
93.75% Branches 60/64
100% Functions 7/7
99.21% Lines 127/128

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280                                                  1x 1x 1x 1x 1x 1x 1x 1x 1x     17x 17x 17x 10x 10x   7x         34x       17x 17x       17x 17x 17x 17x                     84x 84x 84x 170x 76x     84x       17x   17x   17x 17x 17x   17x 15x 8x     15x 2x       17x   17x 17x 17x   17x             17x 10x   7x     17x   17x 17x   17x   17x       51x   51x   51x   51x 34x         51x 28x   23x     51x 51x 51x   51x   51x 51x 51x 51x 51x   51x   51x 7x   7x 3x   4x       51x   51x 60x   51x 51x     51x 16x 16x     51x 2x     49x     51x 7x     44x   26x         51x       51x 28x   23x     51x   34x 18x   16x   34x   51x   51x 20x     18x 18x 18x     31x   31x 24x   31x 31x                         7x 7x 7x 7x 11x   8x 8x   8x 6x   3x 3x 3x 3x 3x 3x     7x 3x   4x        
/*
 * xml-beautify - pretty-print text in XML formats.
 *
 * Copyright (c) 2018 Tom Misawa, riversun.org@gmail.com
 *
 * MIT license:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Usage:
 *
 *       const resultXmlText = new XmlBeautify().beautify(textInput.value,
 *       {
 *            indent: '  ',  //indent pattern like white spaces
 *            useSelfClosingElement: true //true:use self-closing element when empty element.
 *       });
 *
 * How "useSelfClosingElement" property works.
 *
 *   useSelfClosingElement:true
 *   <foo></foo> ==> <foo/>
 *
 *   useSelfClosingElement:false
 *   <foo></foo> ==> <foo></foo>
 *
 */
const ELEMENT_NODE = 1;
const ATTRIBUTE_NODE = 2;
const TEXT_NODE = 3;
const CDATA_SECTION_NODE = 4;
const PROCESSING_INSTRUCTION_NODE = 7;
const COMMENT_NODE = 8;
const DOCUMENT_NODE = 9;
const DOCUMENT_TYPE_NODE = 10;
const DOCUMENT_FRAGMENT_NODE = 11;
export default class XmlBeautify {
  constructor(option) {
    const opt = option || {};
    this.userExternalParser = false;
    if (opt.parser) {
      this.userExternalParser = true;
      this.parser = new opt.parser();
    } else {
      this.parser = new DOMParser();
    }
  }
 
  hasXmlDef(xmlText) {
    return xmlText.indexOf('<?xml') >= 0;
  }
 
  getEncoding(xmlText) {
    const me = this;
    Iif (!me.hasXmlDef(xmlText)) {
      return null;
    }
 
    const encodingStartPos = xmlText.toLowerCase().indexOf('encoding="') + 'encoding="'.length;
    const encodingEndPos = xmlText.indexOf('"?>');
    const encoding = xmlText.substr(encodingStartPos, encodingEndPos - encodingStartPos);
    return encoding;
  }
 
 
  /**
   * Returns Array of ELEMENT_NODE-child
   * @param element
   * @returns {*[]}
   * @private
   */
  _children(element) {
    const _ret = [];
    const numOfChildNodes = element.childNodes.length;
    for (let i = 0; i < numOfChildNodes; i++) {
      if (element.childNodes[i].nodeType === ELEMENT_NODE) {
        _ret.push(element.childNodes[i]);
      }
    }
    return _ret;
  }
 
  beautify(xmlText, data) {
    const me = this;
 
    const doc = me.parser.parseFromString(xmlText, 'text/xml');
 
    let indent = '  ';
    const encoding = 'UTF-8';
    let useSelfClosingElement = false;
 
    if (data) {
      if (data.indent) {
        indent = data.indent;
      }
 
      if (data.useSelfClosingElement == true) {
        useSelfClosingElement = data.useSelfClosingElement;
      }
    }
 
    let xmlHeader = null;
 
    Eif (me.hasXmlDef(xmlText)) {
      const encoding = me.getEncoding(xmlText);
      xmlHeader = '<?xml version="1.0" encoding="' + encoding + '"?>';
    }
    const buildInfo = {
      indentText: indent,
      xmlText: '',
      useSelfClosingElement: useSelfClosingElement,
      indentLevel: 0
    }
 
    if (me.userExternalParser) {
      me._parseInternally(this._children(doc)[0], buildInfo);
    } else {
      me._parseInternally(doc.children[0], buildInfo);
    }
 
    let resultXml = '';
 
    Eif (xmlHeader) {
      resultXml += xmlHeader + '\n';
    }
    resultXml += buildInfo.xmlText;
 
    return resultXml;
  };
 
  _parseInternally(element, buildInfo) {
    const me = this;
 
    let elementTextContent = element.textContent;
 
    const blankReplacedElementContent = elementTextContent.replace(/ /g, '').replace(/\r?\n/g, '').replace(/\n/g, '').replace(/\t/g, '');
 
    if (blankReplacedElementContent.length == 0) {
      elementTextContent = '';
    }
 
 
    let elementHasNoChildren;
    if (me.userExternalParser) {
      elementHasNoChildren = !(me._children(element).length > 0);
    } else {
      elementHasNoChildren = !(element.children.length > 0);
    }
 
    const elementHasValueOrChildren = (elementTextContent && elementTextContent.length > 0);
    const elementHasItsValue = elementHasNoChildren && elementHasValueOrChildren;
    const isEmptyElement = elementHasNoChildren && !elementHasValueOrChildren;
 
    const useSelfClosingElement = buildInfo.useSelfClosingElement;
 
    const startTagPrefix = '<';
    const startTagSuffix = '>';
    const startTagSuffixEmpty = ' />';
    const endTagPrefix = '</';
    const endTagSuffix = '>';
 
    let valueOfElement = '';
 
    if (elementHasItsValue) {
      const { hasCDATAChild, content } = me._getFirstCDATAChild(element);
 
      if (hasCDATAChild) {
        valueOfElement += content;
      } else {
        valueOfElement += elementTextContent;
      }
    }
 
    let indentText = '';
 
    for (let idx = 0; idx < buildInfo.indentLevel; idx++) {
      indentText += buildInfo.indentText;
    }
    buildInfo.xmlText += indentText;
    buildInfo.xmlText += startTagPrefix + element.tagName
 
    //add attributes
    for (let i = 0; i < element.attributes.length; i++) {
      const attr = element.attributes[i];
      buildInfo.xmlText += ' ' + attr.name + '=' + '"' + attr.textContent + '"';
    }
 
    if (isEmptyElement && useSelfClosingElement) {
      buildInfo.xmlText += startTagSuffixEmpty;
 
    } else {
      buildInfo.xmlText += startTagSuffix;
    }
 
    if (elementHasItsValue) {
      buildInfo.xmlText += valueOfElement;
    } else {
 
      if (isEmptyElement && !useSelfClosingElement) {
      } else {
        buildInfo.xmlText += '\n';
      }
 
    }
 
    buildInfo.indentLevel++;
 
    let lengOfChildren;
 
    if (me.userExternalParser) {
      lengOfChildren = me._children(element).length;
    } else {
      lengOfChildren = element.children.length;
    }
 
    for (let i = 0; i < lengOfChildren; i++) {
      let child;
      if (me.userExternalParser) {
        child = me._children(element)[i];
      } else {
        child = element.children[i];
      }
      me._parseInternally(child, buildInfo);
    }
    buildInfo.indentLevel--;
 
    if (isEmptyElement) {
      if (useSelfClosingElement) {
 
      } else {
        const endTag = endTagPrefix + element.tagName + endTagSuffix;
        buildInfo.xmlText += endTag;
        buildInfo.xmlText += '\n';
      }
    } else {
      const endTag = endTagPrefix + element.tagName + endTagSuffix;
 
      if (!(elementHasNoChildren && elementHasValueOrChildren)) {
        buildInfo.xmlText += indentText;
      }
      buildInfo.xmlText += endTag;
      buildInfo.xmlText += '\n';
    }
  };
 
 
  /**
   * Return the CDATA section in the first child element of element.
   * If not exists, returns  { hasCDATAChild:false }
   * @param element
   * @returns {*}
   * @private
   */
  _getFirstCDATAChild(element) {
    const numOfChildNodes = element.childNodes.length;// numOfChildNodes should be 1
    let textContent = ``;
    let hasCDATA = false;
    for (let i = 0; i < numOfChildNodes; i++) {
      if (element.childNodes[i].nodeType === TEXT_NODE) {
 
        const data = element.childNodes[i].data;
        const blankReplacedElementContent = data.replace(/ /g, '').replace(/\r?\n/g, '').replace(/\n/g, '').replace(/\t/g, '');
 
        if (blankReplacedElementContent.length > 0) {
          textContent += element.childNodes[i].data;
        }
      } else Eif (element.childNodes[i].nodeType === CDATA_SECTION_NODE) {
        const data = element.childNodes[i].data;
        textContent += '<![CDATA[';
        textContent += data;
        textContent += ']]>';
        hasCDATA = true;
      }
    }
    if (hasCDATA) {
      return { hasCDATAChild: true, content: textContent };
    }
    return { hasCDATAChild: false };
  }
 
}