XML Element Enumerable Take 2

Friday, May 30, 2008 8:07:53 AM (Mountain Standard Time, UTC-07:00)

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.

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.

#