2013-06-29 29 views
0

我正在努力使用Kendo UI Mobile來映射和顯示XML數據源上的子元素列表。將XML子元素映射到Kendo UI數據源

考慮以下簡單的XML結構:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<topics> 
    <topic id="1" title="Weather"> 
     <header>Great weather today!</header> 
     <smallicon>foo_bar.png</smallicon> 
     <items> 
      <item>It's great weather</item> 
      <item>Sunny feeling</item> 
      <item>Raining like a dog</item> 
     </items> 
    </topic> 

    <topic id="2" title="Politics"> 
     <header>Left or right, take your pick!</header> 
     <smallicon>whatever.png</smallicon> 
     <items> 
      <item>Making budget cuts</item> 
      <item>How important is healthcare?</item> 
     </items> 
    </topic> 
</topics> 

閱讀每一個主題,並將其綁定到一個視圖模板,其實是很容易的。像這樣:

var template = kendo.template($("#home-tpl").html()); 

// hook up to the datasource "change" event; for auto-population 
dataSource.bind("change", function(e) { 
    $("#home-menu").html(kendo.render(template, this.view())); 
}); 

var dataSource = new kendo.data.DataSource({ 
    transport: { 
     read: { 
      url: "topics.xml", 
      dataType: "xml" 
     } 
    }, 
    schema: { 
     type: "xml", 
     data: "/topics/topic", 
     model: { 
      fields: { 
       id: "@id", 
       title: "@title", 
       header: "header/text()", 
       smallicon: "smallicon/text()", 

       // > QUESTION: HOW TO MAP THIS? 
       items: "???" 
      } 
     } 
    } 

dataSource.read(); 

這看起來很好地融合了頂層的屬性和元素。我得到一個主題列表,我可以使用類似#: data.title #的方式將它們綁定到模板。這裏融合而且沒有問題。

但是,我也想爲每個<topic>也映射子元素。在XML示例中,這意味着<items>的列表。這是我感到困惑的「如何映射這個模式」部分。

最終目標是顯示這些子項目的列表,例如:#: data.items[0] #

此外,我試過HierarchicalDataSource,但常規的DataSource似乎工作得很好。也許這會更合適? Kendo API文檔似乎沒有提供具有嵌套層次結構的XML樣本。

有關我如何完成此任務的任何建議?

回答

1

一些試驗和錯誤後,我想出了以下解決方案:

schema: { 
    type: "xml", 
    data: "/topics/topic", 
    model: { 
     fields: { 
      id: "@id", 
      title: "@title", 
      header: "header/text()", 
      smallicon: "smallicon/text()", 

      // > ANWER: THIS IS HOW 
      children: "items" 
     }, 
     hasChildren: "items" 
    } 
} 

現在有兩個變化,這個片段相比,我原來的問題:

  1. 孩子們:「項目「節點被添加到架構
  2. hasChildren:」items「 property

有了這個,一切運行良好,分層結構很好地映射了。作爲獎勵,我現在能做到以下幾點:

 // fetch the one, single topic from the datasource 
     topic = dataSource.Topics.get(topicId); 

     // read the inner contents, e.g. text, from a single <items> node 
     log(topic.children.item[0]["#text"]); 

也許是一些幫助別人的未來...