Mike Taulty's Blog
Bits and Bytes from Microsoft UK
LINQ to XML and IXPathNavigable

Blogs

Mike Taulty's Blog

Elsewhere

Something I've been pondering.

Living over in System.Xml.XPath is an extension method to XNode (from LINQ to XML) called CreateNavigator.

So, given something like an XElement;

XElement x = new XElement("foo");

I can go ahead and get an XPathNavigator from it;

    XElement x = new XElement("foo");
    XPathNavigator nav = x.CreateNavigator();
 

So, how come we do this with an extension method rather than have XNode implement the existing IXPathNavigable? I found that a bit odd and would be interested to know if someone has an explanation.

It's not particularly hard to write a ToNavigable() extension with perhaps something like this (scribbled very quickly);

  public static class Ext
  {
    private class Navigable : IXPathNavigable
    {
      private XNode node;

      public Navigable(XNode n)
      {
        node = n;
      }
      public XPathNavigator CreateNavigator()
      {
        return (node.CreateNavigator());
      }
    }
    public static IXPathNavigable ToNavigable(this XNode n)
    {
      return (new Navigable(n));
    }
  }
and writing that had me thinking about how it would have been "nice" to be able to add this as an extension cast operator to XNode rather than having to write an extension method and then dress it up as above but (AFAIK) that's not something that you can do.
Posted Fri, Nov 30 2007 5:16 AM by mtaulty
Filed under: , ,