Search code examples
xmlsapui5getproperty

Get array from XMLModel in OpenUI5?


How to get array from XMLModel in OpenUI5?

I tried:

  this.oXmlModel = new XMLModel();
  this.oXmlModel.setXML('\
    <data>\
      <items>\
        <item><text1>text 1.1</text1><text2>text 1.2</text2></item>\
        <item><text1>text 2.1</text1><text2>text 2.2</text2></item>\
      </items>\
    </data>\
  ');

  var result1 = oXmlModel.getProperty("/items"));
  var result2 = oXmlModel.getProperty("/items/item"));

Path from result2 is working with bindItems for table. But getProperty with it returns all subnodes in text format.

Working example: http://embed.plnkr.co/wa0oBXbq6Exfj3NqNKmQ/ (see ui/App.controller.js)


Solution

  • XML has no arrays and defines lists as multiple elements. You will have have to use the getObject method which will return you the XML object for the given property. You will then have to convert this XML to JSON with a conversion routine. Here is a XML to JSON converter based on David Walsh's blog post

    onInit: function (evt) {
      ...
      ...
      var result1 = this.oXmlModel.getObject("/items");
      console.log(this.xmlToJson(result1));
      ...
    },
    
    xmlToJson : function(xml) {
    
        // Create the return object
        var obj = {};
    
        if (xml.nodeType == 1) { // element
            // do attributes
            if (xml.attributes.length > 0) {
            obj["@attributes"] = {};
                for (var j = 0; j < xml.attributes.length; j++) {
                    var attribute = xml.attributes.item(j);
                    obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
                }
            }
        } else if (xml.nodeType == 3) { // text
            obj = xml.nodeValue;
        }
    
        // do children
        if (xml.hasChildNodes()) {
            for(var i = 0; i < xml.childNodes.length; i++) {
                var item = xml.childNodes.item(i);
                var nodeName = item.nodeName;
                if (typeof(obj[nodeName]) == "undefined") {
                    obj[nodeName] = xmlToJson(item);
                } else {
                    if (typeof(obj[nodeName].push) == "undefined") {
                        var old = obj[nodeName];
                        obj[nodeName] = [];
                        obj[nodeName].push(old);
                    }
                    obj[nodeName].push(xmlToJson(item));
                }
            }
        }
        return obj;
    }