XML Element Enumerable Take 2

Posted on May 30, 2008 @ 15:07 csharp oop

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 Adam, he suggested that I simplify the implementation with a little XPath action.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  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.