AnalyticsApi.AnalyticsGoalParser.ParseCompletions C# (CSharp) Method

ParseCompletions() public method

public ParseCompletions ( string xml ) : int>.Dictionary
xml string
return int>.Dictionary
        public Dictionary<int, int> ParseCompletions(string xml)
        {
            var dictionary = new Dictionary<int, int>();

            var doc = XDocument.Parse(xml);
            var ns = doc.Root.GetDefaultNamespace();
            var prefix = doc.Root.GetNamespaceOfPrefix("dxp");

            var nodes = doc.Root.Descendants(ns + "entry");

            if(nodes.Any())
            {
                var node = nodes.First();
                var metrics = node.Descendants(prefix + "metric");

                if(metrics.Any())
                {
                    foreach(var metric in metrics)
                    {
                        var number = metric.Attribute("name").Value.Replace("ga:goal", string.Empty).Replace("Completions", string.Empty);

                        if (number == "ga:visits")
                            continue;

                        var completions = metric.Attribute("value").Value;

                        try
                        {
                            dictionary.Add(int.Parse(number), int.Parse(completions));
                        }
                        catch(ArgumentException ex)
                        {
                            // Swallow
                        }
                    }
                }
            }

            return dictionary;
        }

Usage Example

        public IEnumerable <Goal> GetGoalCompletions(IEnumerable <Goal> goals, string start, string end)
        {
            var metrics = "ga%3Avisits,";

            foreach (var goal in goals)
            {
                metrics += "ga%3Agoal" + goal.Number + "Completions,";
            }

            metrics = metrics.TrimEnd(',');

            var data = _dataProvider.SendRequest(_token, "https://www.google.com/analytics/feeds/data?ids=ga%3A" + _profile.Value + "&metrics=" + metrics + "&start-date=" + start + "&end-date=" + end + "&max-results=50");

            var parser = new AnalyticsGoalParser();
            var visits = parser.ParseVisits(data);

            var completions = parser.ParseCompletions(data);

            foreach (var completion in completions)
            {
                var goal = goals.FirstOrDefault(x => x.Number == completion.Key);
                goal.Completions    = completion.Value;
                goal.ConversionRate = Math.Round((completion.Value / (double)visits) * 100, 2);

                yield return(goal);
            }
        }
All Usage Examples Of AnalyticsApi.AnalyticsGoalParser::ParseCompletions