CSharp examples for System.Xml:XML Element
Filters the collection of elements by XML attribute.
using System.Xml.Linq; using System.Linq; using System.Collections.Generic; public class Main{ /// <summary> /// Filters the collection of elements by attribute. /// </summary> /// <param name="elements">The elements to filter.</param> /// <param name="attributeName">Name of the attribute.</param> /// <param name="value">The value.</param> /// <returns>A filtered list of elements containing the given attribute with the given value.</returns> public static List<XElement> FilterByAttribute(this IEnumerable<XElement> elements, string attributeName, string value) {// w w w . ja v a 2 s. co m return FilterByAttribute(elements, (XName)attributeName, value); } /// <summary> /// Filters the collection of elements by attribute. /// </summary> /// <param name="elements">The elements to filter.</param> /// <param name="attributeName">Name of the attribute.</param> /// <param name="value">The value.</param> /// <returns>A filtered list of elements containing the given attribute with the given value.</returns> public static List<XElement> FilterByAttribute(this IEnumerable<XElement> elements, XName attributeName, string value) { List<XElement> filteredElements = new List<XElement>(); foreach (XElement currentElement in elements) { XAttribute targetAttribute = currentElement.Attribute(attributeName); if (targetAttribute != null && targetAttribute.Value == value) { filteredElements.Add(currentElement); } } return filteredElements; } /// <summary> /// Filters the collection of elements by attribute. /// </summary> /// <param name="elements">The elements to filter.</param> /// <param name="attributeName">Name of the attribute.</param> /// <returns>A filtered list of elements containing the given attribute.</returns> public static List<XElement> FilterByAttribute(this IEnumerable<XElement> elements, string attributeName) { List<XElement> filteredElements = new List<XElement>(); foreach (XElement currentElement in elements) { XAttribute targetAttribute = currentElement.Attribute(attributeName); if (targetAttribute != null) { filteredElements.Add(currentElement); } } return filteredElements; } }