Filters a list of XElements to a subset which match ALL of the given attributes - CSharp System.Xml

CSharp examples for System.Xml:XML Element

Description

Filters a list of XElements to a subset which match ALL of the given attributes

Demo Code


using System.Xml.Linq;
using System.Linq;
using System.Collections.Generic;

public class Main{
        #region?Methods?(7)//from   w w w . ja  va 2s .  co m

        //?Public?Methods?(7)?

        /// <summary>
        /// Filters a list of XElements to a subset which match ALL of the given attributes
        /// </summary>
        /// <param name="elements"></param>
        /// <param name="attributeNames"></param>
        /// <returns></returns>
        public static List<XElement> FilterByAllAttributes(this IEnumerable<XElement> elements, List<string> attributeNames)
        {
            List<XElement> filteredElements = new List<XElement>();

            foreach (XElement currentElement in elements)
            {
                bool satisfiesAllAttributes = true;

                //Check each attribute for the element
                foreach (string attribute in attributeNames)
                {
                    XAttribute nextAttribute = currentElement.Attribute(attribute);
                    if (nextAttribute == null)
                    {
                        satisfiesAllAttributes = false;
                        break;
                    }
                }

                if (satisfiesAllAttributes)
                {
                    filteredElements.Add(currentElement);
                }
            }

            return filteredElements;
        }
}

Related Tutorials