xmlToJson

This tag traverses the XML and tries to convert it to JSON.

Created by: hackvertor
Installed 1 times

Category: XML

Created on: Tuesday, October 15, 2024 at 8:31:28 PM

Updated on: Tuesday, October 15, 2024 at 8:31:28 PM

This is a built in tag
Tag arguments
[]
Code
class xmlToJson {
  encode(xmlString) {
    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(xmlString, "text/xml");

    function xmlToJson(node) {
      const obj = {};

      if (node.nodeType === 1) {
        if (node.attributes.length > 0) {
          obj["@attributes"] = {};
          for (let i = 0; i < node.attributes.length; i++) {
            const attr = node.attributes.item(i);
            obj["@attributes"][attr.nodeName] = attr.nodeValue;
          }
        }
      } else if (node.nodeType === 3) {
        return node.nodeValue.trim(); // Return the text content
      }

      if (node.hasChildNodes()) {
        for (let i = 0; i < node.childNodes.length; i++) {
          const child = node.childNodes.item(i);
          const childJson = xmlToJson(child);

          if (childJson === "") continue;

          if (obj[child.nodeName]) {
            if (!Array.isArray(obj[child.nodeName])) {
              obj[child.nodeName] = [obj[child.nodeName]];
            }
            obj[child.nodeName].push(childJson);
          } else {
            obj[child.nodeName] = childJson;
          }
        }
      }

      return obj;
    }
    const jsonResult = xmlToJson(xmlDoc.documentElement);
    return JSON.stringify(jsonResult, null, 3);
  }
}