Select Elements via xpath - CSharp System.Xml

CSharp examples for System.Xml:XML Element

Description

Select Elements via xpath

Demo Code


using System.Xml.Linq;
using System.Threading.Tasks;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;/*from   w  w w .  j a  v  a 2s.  c  om*/

public class Main{
        public static IEnumerable<XElement> SelectElements(XElement doc, string path)
        {
            IEnumerable<XElement> res = null;
            if (string.IsNullOrEmpty(path))
            {
                return res;
            }
            var tracks = path.Split('/');
            res = doc.Elements(tracks[0]);
            if (tracks.Length > 1)
            {
                List<XElement> temp = new List<XElement>();
                foreach (var elem in res)
                {
                    temp.AddRange(SelectElements(elem, string.Join("/", tracks, 1, tracks.Length - 1)));
                }
                res = temp;
            }
            return res;
        }
}

Related Tutorials