30 May 2008

XML Element Enumerable Take 2

by mo

A couple of days ago I posted something on an XmlEnumerable. An object that knows how to traverse an XML document in a linear form. After talking with a colleage, he suggested that I simplify the implementation with a little XPath action.

  public class XmlElementEnumerable : IEnumerable<IXmlElement> {
      private XmlElement rootElement;
      private IMapper<XmlElement, IXmlElement> mapper;

      public XmlElementEnumerable(XmlElement rootElement) {
          this.rootElement = rootElement;
          mapper = new XmlElementMapper();

      public IEnumerator<IXmlElement> GetEnumerator() {
          foreach (var node in rootElement.SelectNodes("//*")) {
              yield return mapper.MapFrom(node.DownCastTo<XmlElement>());

      IEnumerator IEnumerable.GetEnumerator() {
          return GetEnumerator();

Diving a little deeper, I think using XPath expressions are probably a lot more efficient for traversing a document.

csharp oop