PageRenderTime 41ms CodeModel.GetById 11ms app.highlight 3ms RepoModel.GetById 17ms app.codeStats 0ms

/silverlight/test.xunit-silverlight/Compatibility/Silverlight3/MissingMethods/System.Xml.XPath.Extensions.cs

#
C# | 38 lines | 28 code | 4 blank | 6 comment | 0 complexity | b2860c908b413c288850fd2e32a8ad5f MD5 | raw file
 1using System.Collections.Generic;
 2using System.Xml.Linq;
 3using System.Linq;
 4
 5namespace System.Xml.XPath
 6{
 7    internal static class Extensions
 8    {
 9        // VERY simple xpath helper method. Only useful for VERY simple expressions. Like what we need.
10        // Thanks to Chris Cavanagh: http://chriscavanagh.wordpress.com/2009/04/11/micro-xpath-almost-in-silverlight-2/
11        public static XElement XPathSelectElement(this XElement element, string expression)
12        {
13            return expression.Split('/').Aggregate(element, (e, name) => e.Element(name));
14        }
15
16        public static IEnumerable<XElement> XPathSelectElements(this XElement element, string expression)
17        {
18            // Split expression in parts
19            // Get candidate elements for first part
20            // Interrogate each candidate for 2nd part => new candidates
21            // Interrogate each candidate for 3rd part
22
23            var candidates = new List<XElement> {element};
24            var parts = expression.Split('/');
25            foreach (var part in parts)
26            {
27                var newCandidates = new List<XElement>();
28                foreach (var candidate in candidates)
29                {
30                    newCandidates.AddRange(candidate.Elements(part));
31                }
32                candidates = newCandidates;
33            }
34
35            return candidates;
36        }
37    }
38}