C # XML XDocument

I am encoding a media player in C #, so I saved the playlists in XML, as shown below:

XML

So, I want to get the attributes of the playlist "name" and the attribute "path" of the media.

I can get both codes:

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 the following:

Movies

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, get only links that match the movies.

+4
source share
1 answer

Used combination with SelectMany and GroupBy.

SelectMany , , GroupBy , , , Where, name, .

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);
    }
}
+4

Source: https://habr.com/ru/post/1622909/


All Articles