aboutsummaryrefslogtreecommitdiff
path: root/Aggregator/Parser/ParserService.cs
blob: 06f34694c5aa77bd5449ac822bcaf5eba993545e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
using Classes;

namespace Aggregator.Parser {
    /// <summary>
    /// Class to provide Parsing services
    /// </summary>
    public static class ParserService {

        /// <summary>
        /// Parse a single xml code, given a config, to Articles
        /// </summary>
        /// <param name="xml">XML code from an RSS feed</param>
        /// <param name="config">Config that tells parser where to get relevant information</param>
        /// <returns>Parsed articles from XML code</returns>
        public static IEnumerable<Article> Parse(string xml, Config config) {

            return XDocument.Parse(xml).Descendants("item") //make an XDocument out of the xml
                .Select(articles => articles.Descendants().ToArray()) //turn each 'item' into it's respective descendants
                .Select(article => new Article() //make a new article from each 'item' article, using config for pointers
                {
                    Source = config.Source,
                    Title = article[config.Title].Value,
                    Description = article[config.Description].Value,
                    ArticleLink = article[config.ArticleLink].Value,
                    ImageLink = article[config.ImageLink].Attribute("url").Value,
                    PublishDate = DateTime.Parse(article[config.PublishDate].Value)
                }).Distinct(); //remove any duplicates
        }

        /// <summary>
        /// Parse multiple xml sets, given a similar set of configs, to Articles
        /// </summary>
        /// <param name="xmls">Array of XML sets to parse for Articles</param>
        /// <param name="configs">List of configs to parse for corresponding xml sets</param>
        /// <returns>Parsed articles from every XML set</returns>
        public static IEnumerable<Article> ParseMultiple(string[] xmls, List<Config> configs) {
            if (configs.Count == 0 || xmls.Length == 0 || (xmls.Length != configs.Count)) { 
                return null; //for bad cases
            }
            else {
                return xmls.Select((xml, index) => Parse(xml, configs[index])) //Parse each item
                    .SelectMany(i => i); //remove distinctions between each set of articles
            }
        }
    }
}