formatXml

This tag formats an XML string by parsing it into a DOM structure, recursively traversing its nodes, and adding appropriate indentation and line breaks for elements, text, attributes, and comments, ensuring readable, structured output.

Created by: hackvertor
Installed 1 times

Category: XML

Created on: Tuesday, October 22, 2024 at 7:19:27 PM

Updated on: Wednesday, November 6, 2024 at 2:17:29 PM

This is a built in tag
Tag arguments
[
   {
      "type": "number",
      "help": "This provides the indent size",
      "defaultValue": "2"
   }
]
Code
class formatXml {
  encode(xmlString, indentSize) {
    const doc = new DOMParser().parseFromString(xmlString, "text/xml");
    return formatNode(doc.documentElement, 0, indentSize);
    function formatNode(node, level, indentSize) {
      let result = "";
      const indent = " ".repeat(level * indentSize);

      if (node.nodeType === 1) {
        result += `${indent}<${node.nodeName}`;

        if (node.attributes.length > 0) {
          for (let i = 0; i < node.attributes.length; i++) {
            const attr = node.attributes[i];
            result += ` ${attr.name}="${attr.value}"`;
          }
        }

        if (node.childNodes.length === 0) {
          result += " />\n";
        } else {
          result += ">\n";

          for (let i = 0; i < node.childNodes.length; i++) {
            result += formatNode(node.childNodes[i], level + 1, indentSize);
          }

          result += `${indent}</${node.nodeName}>\n`;
        }
      } else if (node.nodeType === 3) {
        const text = node.nodeValue.trim();
        if (text.length > 0) {
          result += `${indent}${text}\n`; 
        }
      } else if (node.nodeType === 8) {
        result += `${indent}<!-- ${node.nodeValue.trim()} -->\n`;
      }

      return result;
    }
  }
}