Filter by the given XML attributes OR the local name - CSharp System.Xml

CSharp examples for System.Xml:XML Attribute

Description

Filter by the given XML attributes OR the local name

Demo Code


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

public class Main{
        /// <summary>
        /// Filter by the given attributes OR the local name
        /// </summary>
        /// <param name="elements"></param>
        /// <param name="localName"></param>
        /// <param name="attributeName1"></param>
        /// <param name="attributeName2"></param>
        /// <returns></returns>
        public static List<XElement> FilterByLocalNameOrAttributes(this IEnumerable<XElement> elements,
                                                                   string localName, string attributeName1, string attributeName2)
        {/*  ww w .j  a va2 s.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 (currentElement.Name.LocalName == localName || targetAttribute1 != null || targetAttribute2 != null)
                {
                    filteredElements.Add(currentElement);
                }
            }

            return filteredElements;
        }
}

Related Tutorials