简体   繁体   English

C#XML XDocument

[英]C# XML XDocument

I am coding a media player in C# so I saved playlists in an XML as below : 我正在使用C#编写媒体播放器,因此我将播放列表保存为XML,如下所示:

XML

So I want to get attributes of playlist "name" and attribute of media "path". 所以我想得到播放列表“名称”的属性和媒体“路径”的属性。

I am able to get both using this code : 我能够使用这段代码得到两个:

var xdoc = XDocument.Load(@"mypath");

var names = from i in xdoc.Descendants("playlist")
            select new
            {
                Path = (string)i.Attribute("name")
            };

var paths = from i in xdoc.Descendants("media")
            select new
            {
                Path = (string)i.Attribute("path")
            };

foreach (var name in names)
{
    System.Diagnostics.Debug.WriteLine(name.Path);
    foreach (var path in paths)
        System.Diagnostics.Debug.WriteLine(path.Path);
}

So I get this : 所以我明白了:

Films 电影

E:\Projets\CS - MyWindowsMediaPlayer\Example Medias\Music1.mp3
E:\Projets\CS - MyWindowsMediaPlayer\Example Medias\MusicInfos1.mp3
E:\Projets\CS - MyWindowsMediaPlayer\Example Medias\Video2.mp4
E:\Projets\CS - MyWindowsMediaPlayer\Example Medias\Video1.mp4
E:\Projets\CS - MyWindowsMediaPlayer\Example Medias\Video3.mp4

But I want to sort by categories, for example getting only links that corresponds with films. 但我想按类别排序,例如只获取与电影相对应的链接。

Lets use a combination with SelectMany and GroupBy. 让我们使用SelectMany和GroupBy的组合。

The SelectMany will create a single list, with a tuple containing the playlist name and the media path, then we use GroupBy to group this list by playlist name, and finally we can use the Where to filter only the playlist with a given name, in this case, Films . SelectMany将创建一个列表,其中包含播放列表名称和媒体路径的元组,然后我们使用GroupBy按播放列表名称对此列表进行分组,最后我们可以使用Where仅过滤具有给定名称的播放列表,这个案子, 电影

var xdoc = XDocument.Load(@"mypath");

var paths = xdoc.Descendants("playlist")
                .SelectMany(x => x.Descendants("media"), (pl, media) => Tuple.Create(pl.Attribute("name").Value, media.Attribute("path").Value))
                .GroupBy(x => x.Item1)
                .ToList();

foreach (var name in paths.Where(x => x.Key == "Films"))
{
    Console.WriteLine(name.Key);
    foreach (var tuple in name)
    {
        Console.WriteLine(tuple.Item2);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM