简体   繁体   English

从OpenUI5中的XMLModel获取数组?

[英]Get array from XMLModel in OpenUI5?

How to get array from XMLModel in OpenUI5? 如何从OpenUI5中的XMLModel获取数组?

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. result2的路径正在使用表的bindItems。 But getProperty with it returns all subnodes in text format. 但是,带有它的getProperty会以文本格式返回所有子节点。

Working example: http://embed.plnkr.co/wa0oBXbq6Exfj3NqNKmQ/ (see ui/App.controller.js) 工作示例: http ://embed.plnkr.co/wa0oBXbq6Exfj3NqNKmQ/(请参见ui / App.controller.js)

XML has no arrays and defines lists as multiple elements. XML没有数组,并且将列表定义为多个元素。 You will have have to use the getObject method which will return you the XML object for the given property. 您将必须使用getObject方法,该方法将为给定属性返回XML对象。 You will then have to convert this XML to JSON with a conversion routine. 然后,您将不得不使用转换例程将此XML转换为JSON。 Here is a XML to JSON converter based on David Walsh's blog post 这是基于David Walsh的博客文章的XML到JSON转换器

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM