2011-09-20 78 views
0

我有一个有多个记录的XML。我想使用下面的代码将这些记录填充到列表框中。Windows Phone 7 XML填充到列表框查询

void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
     { 
      if (e.Error != null) 
      { 
       System.Diagnostics.Debug.WriteLine("Error: "+e); 
      } 
       XElement coupon = XElement.Parse(e.Result); 

       MainListBox.ItemsSource = from query in coupon.Descendants("cs") 
              select new ViewModels.LoadCoupon() 
              { 
               CouponName = (string)query.Element("c").Attribute("t"), 
               //MerchantImage = dB.getBaseUri() + "images/merchant/" + (string)query.Element("ms").Element("m").Element("id") 
               MerchantImage = dB.getBaseUri() + "images/merchant/" + (string)query.Element("c").Attribute("mId") + ".png" 
              }; 

     } 

其中MainListBox是我的列表框。使用上面的代码,我只能填充一条记录。我知道我错过了一些东西。任何人都可以让我知道我需要做什么才能显示XML中的多个记录。我已经复制了我正在使用的示例XML。谢谢。

<d> 
     <ms> 
     <m id="9921" n="The Book Company" /> 
     <m id="6333" n="Earth Rental" /> 
     <m id="6329" n="The Organic Baker" /> 
     <m id="6331" n="News Stand" /> 
     <m id="6327" n="The Jam Company" /> 
     <m id="6325" n="The Fruit Company" /> 
     </ms> 
     <cs> 
     <c id="14533" mId="9921" t="50% Off Any Book Purchase"> 
      <ls> 
      <l id="40145" lng="-0.0724" lat="51.5024" d="4.97" dim="45.91" intX="" intY="" intL="" /> 
      </ls> 
      <cats> 
      <cat id="41" /> 
      <cat id="43" /> 
      </cats> 
      <as /> 
     </c> 
<c id="14533" mId="9921" t="50% Off Any Book Purchase"> 
       <ls> 
       <l id="40145" lng="-0.0724" lat="51.5024" d="4.97" dim="45.91" intX="" intY="" intL="" /> 
       </ls> 
       <cats> 
       <cat id="41" /> 
       <cat id="43" /> 
       </cats> 
       <as /> 
      </c> 
<c id="14533" mId="9921" t="50% Off Any Book Purchase"> 
       <ls> 
       <l id="40145" lng="-0.0724" lat="51.5024" d="4.97" dim="45.91" intX="" intY="" intL="" /> 
       </ls> 
       <cats> 
       <cat id="41" /> 
       <cat id="43" /> 
       </cats> 
       <as /> 
      </c> 
     </cs> 
    </d> 

回答

3

您只有一个cs元素,所以它只产生一个元素。我想你想要这样的:

// Note the use of Descendants("c") here 
MainListBox.ItemsSource = from query in coupon.Descendants("c") 
          select new ViewModels.LoadCoupon() 
          { 
           CouponName = (string)query.Attribute("t"), 
           MerchantImage = dB.getBaseUri() + 
               "images/merchant/" + 
               (string)query.Attribute("mId") + 
               ".png" 
          }; 

编辑:为了找到一个特定的元素,我会使用:

var match = coupon.Descendants("c") 
        .Where(c => (string) c.Attribute("mId") == mId) 
        .Single(); 
+0

那真棒谢谢。你能否也请告诉我如何使用属性的值来获取元素。例如在我得到mId的Linkq查询中,我想要使用我已经在循环中使用的mId来获取元素及其名称。谢谢。 – Karthik

+0

@Karthik:将编辑。 –