0

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)

endrx
  • 17
  • 6

1 Answers1

0

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;
}
Stephen S
  • 3,936
  • 2
  • 23
  • 33
  • Thanks, this is useful code and link. But in my particular case I need to get all XML subelements as JS array, and later return them to XML element (replacing modified), if necessary. Also, now I think, that just copying subelements in any form and replacing them back later, will do. Because my need is to backup items, and return them, if user cancels changes. – endrx Mar 17 '17 at 12:33
  • That is possible with a custom parser which creates an array for your XML code but it be kinda fixed for a particular structure of an XML block. – Stephen S Mar 17 '17 at 12:42