2011-11-30 45 views
2

我使用下面如何讓小部件的指數,它爲什麼只給第一個值

string xml = @"<?xml version='1.0' encoding='UTF-8'?> 
<widgets> 
    <widget> 
     <url>~/Portal/Widgets/ServicesList.ascx</url> 
     <castAs>ServicesWidget</castAs> 
     <urlType>ascx</urlType> 
     <parameters> 
      <PortalCategoryId>3</PortalCategoryId> 
     </parameters> 
    </widget> 
    <widget> 
     <url>www.omegacoder.com</url> 
     <castAs>ServicesWidget</castAs> 
     <urlType>htm</urlType> 
     <parameters> 
      <PortalCategoryId>41</PortalCategoryId> 
     </parameters> 
    </widget> 
</widgets>"; 

XDocument loaded = XDocument.Parse(xml); 

var widgets = from x in loaded.Descendants("widget") 
       select new 
       { 
        URL = x.Descendants("url").First().Value, 
        Category = x.Descendants("PortalCategoryId").First().Value 
       }; 

foreach (var wd in widgets) 
    Console.WriteLine("Widget at ({0}) has a category of {1}", wd.URL, wd.Category); 

代碼這讓我對只有第一個插件的網址和類別?不知道如何獲得第二個值。 另外我怎樣才能得到像0和1等小部件的索引....取決於有多少小部件。

感謝

回答

2

兩個部件對我的查詢返回條目中,我已經試過你的代碼沒有任何變化。

下面的查詢將幫助您爲每個插件獲取指數以及:

var widgets = loaded.Descendants("widget").Select((w, i) => 
        new 
        {   
        WidgetIndex = i, 
        URL = w.Descendants("url") 
          .FirstOrDefault() 
          .Value, 
        Category = w.Descendants("PortalCategoryId") 
           .FirstOrDefault() 
           .Value 
        }); 

字符串表示:

string widgetsInfo = 
    loaded.Descendants("widget") 
      .Select((w, i) => 
       new 
        { 
         WidgetIndex = i, 
         URL = w.Descendants("url").FirstOrDefault().Value, 
         Category = w.Descendants("PortalCategoryId").FirstOrDefault().Value 
        }) 
      .Select(w => String.Format("Index:{0}; URL:{1}; CATEGORY:{2}; ", 
             w.WidgetIndex, w.URL, w.Category)) 
      .Aggregate((acc, next) => acc + Environment.NewLine + next); 
+0

我想你將它添加到列表中。我將如何爲值和索引做一個消息框,以便我知道它們在應用程序中是正確的 – Autolycus

+0

您將擁有一個匿名類型的項目列表,您是否有某種類的小部件類?否則,只是把所有的字符串,所以這將作爲'List ' – sll

+0

我沒有一個小部件類。我是C#的新手,不知道多少參數。我將如何將其轉換爲數組。因爲我需要將它發送到一個數組中的不同方法 – Autolycus

相關問題