Linq to Xml按标签分组

时间:2011-11-25 16:17:55

标签: xml tags linq-to-xml

我有一个类似于这个的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

如果有第二个日期,那么也打印它:

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 个答案:

答案 0 :(得分: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