Forum

Convert XML to JSON
 
Notifications
Clear all

Convert XML to JSON

2 Posts
2 Users
4 Reactions
311 Views
(@hackbart)
Posts: 24
Trusted Member
Topic starter
 

Hi,

I did not found a solution without using a framework, so I thought maybe somebody else might find this helpful:

function XmlToJson(const AXmlString: string): string;
begin
  asm
    var parser = new DOMParser();
    var xmlDoc = parser.parseFromString(@AXmlString, "text/xml");

    var json = {};
    if (xmlDoc.firstChild) {
      json[xmlDoc.firstChild.nodeName] = parseNode(xmlDoc.firstChild);
    }

    function parseNode(node) {
      var result = {}
;
      if (node.childNodes.length === 0) {
        result = node.textContent;
      }
 else {
        for (var i = 0; i < node.childNodes.length; i++) {
          var child = node.childNodes[i];
          if (child.nodeType === Node.ELEMENT_NODE) {
            if (result[child.nodeName] === undefined) {
              result[child.nodeName] = parseNode(child);
            }
 else {
              if (!Array.isArray(result[child.nodeName])) {
                result[child.nodeName] = [result[child.nodeName]];
              }
              result[child.nodeName].push(parseNode(child));
            }
          }
        }
      }
      return result;
    }

  @result = JSON.stringify(json);
 end;
end;
 
Posted : 19/05/2023 3:02 pm
Jon Lennart Aasenden
(@tao4all)
Posts: 44
Member Admin
 

Everything in JS is json based. Its the foundation for all JS objects, even prototypes. XML is likewise built in, but you have to work it the way you have done in your example here.
There are wrapper classes in the RTL to simplify this 🙂

 
Posted : 11/08/2023 11:12 am
Lou reacted
Share: