XPath (barely) in Silverlight 2

If you need to perform very simple element-only XPath queries in Silverlight 2.0, this extension method might help:

/// <summary>
/// Selects an <see cref="XElement"/> using a non-attributed Micro XPath (MXPath) expression.
/// </summary>
/// <remarks>This is a very simplistic Micro XPath (http://senzhang.netfirms.com/mxpath.htm) implementation.</remarks>
/// <param name="element">The element.</param>
/// <param name="xpath">The xpath.</param>
/// <returns>Returns the element, or null if not found.</returns>
public static XElement MMXPathSelectElement( this XContainer element, string xpath )
{
    return xpath.Split( '/' ).Aggregate( element, ( e, name ) => e.Element( name ) ) as XElement;
}

As you can see it only supports a simple element path (like root/child1/child2) so attributes and complex expressions wonโ€™t work, but you might still find a use for it (I did! ๐Ÿ™‚ ).

3 Comments

Leave a comment