2011-11-25 73 views
0

我有類似這樣的一個xml:的LINQ到XML分組按標籤

<data> 
<date>24/11</date> 
<info>Info I want to get</info> 
<info>Info I want to get</info> 
<info>Info I want to get</info> 

<date>25/11</date> 
<info>Info I want to get</info> 
<info>Info I want to get</info> 
<info>Info I want to get</info> 
</data> 

的事情是,即時通訊能夠得到所有的信息標籤,但我得到的所有日期的結果。

我不知道日期會是什麼,因爲它們是動態生成的。我知道的是,我可能有一個數據標籤與一個或兩個日期標籤


我希望我可以顯示列表框上的第一個日期的信息和另一個列表框上的第二個日期的信息。我怎樣才能做到這一點?

理想的輸出:

textbox with the first date 

value of tag info related to the first date 
value of tag info related to the first date 
value of tag info related to the first date 

如果there's第二次約會,然後打印太:

textbox with the second date 

value of tag info related to the second date 
value of tag info related to the second date 
value of tag info related to the second date 

THX!

回答

1

我不知道什麼樣的ListBox(如Windows窗體,ASP.NET,WPF)要填充,所以我只是告訴你如何組XML輸入:

XDocument input = XDocument.Load("../../XMLFile4.xml"); 
    var groups = 
     from info in input.Root.Elements("info") 
     group info by info.ElementsBeforeSelf("date").Last() into g 
     select new 
     { 
      date = (string)g.Key, 
      infos = (from infoEl in g select (string)infoEl).ToList() 
     }; 

    foreach (var item in groups) 
    { 
     Console.WriteLine("Date: {0}", item.date); 
     foreach (string info in item.infos) 
     { 
      Console.WriteLine("\t{0}", info); 
     } 
    } 

輸出則是例如

Date: 24/11 
     Info I want to get 
     Info I want to get 
     Info I want to get 
Date: 25/11 
     Info I want to get 
     Info I want to get 
     Info I want to get 
+0

對不起,我忘了說它的Windows手機應用程序。我會試試這個! –

+0

那麼,它不是我真正需要的,但是,方法ElementsBeforeSelf遊戲的意識,所以我可以做一些過濾在這裏。真正的XML數據比這更復雜一點。謝謝! –