Filter by one attribute _OR_ a second attribute TODO: rename this to something else, and make a list version that takes a list array of attributes and ors over TODO: all of them - CSharp System.Xml

CSharp examples for System.Xml:XML Attribute

Description

Filter by one attribute _OR_ a second attribute TODO: rename this to something else, and make a list version that takes a list array of attributes and ors over TODO: all of them

Demo Code


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

public class Main{
        /// <summary>
        /// Filter by one attribute _OR_ a second attribute
        /// TODO: rename this to something else, and make a list version that takes a list/array of attributes and ors over
        /// TODO: all of them
        /// </summary>
        /// <param name="elements"></param>
        /// <param name="attributeName1"></param>
        /// <param name="attributeName2"></param>
        /// <returns></returns>
        public static List<XElement> FilterByAnyAttributes(this IEnumerable<XElement> elements,
                                                           string attributeName1, string attributeName2)
        {//ww  w .  j a  va2s.  c  o m
            List<XElement> filteredElements = new List<XElement>();

            foreach (XElement currentElement in elements)
            {
                XAttribute targetAttribute1 = currentElement.Attribute(attributeName1);
                XAttribute targetAttribute2 = currentElement.Attribute(attributeName2);

                if (targetAttribute1 != null || targetAttribute2 != null)
                {
                    filteredElements.Add(currentElement);
                }
            }

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

            foreach (XElement currentElement in elements)
            {
                //Check each attribute for the element
                foreach (string attribute in attributeNames)
                {
                    XAttribute nextAttribute = currentElement.Attribute(attribute);
                    if (nextAttribute != null)
                    {
                        filteredElements.Add(currentElement);
                        break;
                    }
                }
            }

            return filteredElements;
        }
}

Related Tutorials