如何迭代DataSchema XML的数据输出

时间:2013-05-21 18:39:22

标签: javascript xml yui

YUI().use("datatype-xml", "dataschema-xml", function(Y)
{
    var dataIn = Y.DataType.XML.parse(xmlData);
    schema = {
        resultListLocator: "song",
        resultFields: [{key:"title"}, {key:"artist"}, {key:"rank"}]
    },
    dataOut = Y.DataSchema.XML.apply(schema, dataIn);

    console.log(dataOut); <-- Display list of object
    console.log(dataOut.length); <--- Undefined
});

当我仅记录dataOut(对象列表)时,一切似乎都是正确的。但是当我尝试遍历该列表时,长度是未定义的。

那么在应用DataSchema.XML后如何迭代列表呢?

1 个答案:

答案 0 :(得分:2)

DataSchema的apply方法返回具有resultsmeta属性的对象。 results属性是一个可以迭代的数组。这是一个例子:

YUI().use("datatype-xml", "dataschema-xml", function(Y) {
  var data_in = Y.DataType.XML.parse('<Response><Session>542235629</Session><Tracks  start="1" count="10" total="98" errorCount="0"  defaultSort="popularity+"  description="Top 100 Tracks"  name="Top 100 Tracks"  ><Track id="59672468" rating="-1" title="I Kissed A Girl"><Artist id="30326214" rating="-1">Katy Perry</Artist><ItemInfo><ChartPosition last="26" this="1"/></ItemInfo></Track><Track id="47973564" rating="-1" title="Shake It"><Artist id="45575683" rating="-1">Metro Station</Artist><ItemInfo><ChartPosition last="27" this="2"/></ItemInfo></Track><Track id="52207363" rating="-1" title="Bleeding Love"><Artist id="37956508" rating="-1">Leona Lewis</Artist><ItemInfo><ChartPosition last="28" this="3"/></ItemInfo></Track></Tracks></Response>'),
      schema = {
        metaFields: {
          session: "//Session", total:"//Tracks/@total"
        },
        resultListLocator: "//Track",
        resultFields: [
          {key:"song", locator:"@title"},
          {key:"artist", locator:"Artist"},
          {key:"rank", locator:"ItemInfo/ChartPosition/@this"}
        ]
      },
      data_out = Y.DataSchema.XML.apply(schema, data_in);

  Y.Array.each(data_out.results, function (data) {
    // ...
  })
});