May 29, 2003

On implementing custom XsltContext when extending XPath

Here is another easy-to-solve-when-you-know-what-is-wrong problem. It took me couple of hours to find the solution, so I wanna share it. Hope it'll be useful to anybody.

The problem. When adding custom XPath extension functions as described in "HOW TO: Implement and Use Custom Extension Functions When You Execute XPath Queries in Visual C# .NET" KB article and "Adding Custom Functions to XPath" article at MSDN Extreme XML column you can find that any XPath expressions having namespace prefixes, like "/foo:bar" just can't be evaluated due to nasty System.ArgumentNullException deeply in the XPath engine.

The reason. It turned out that internal XPath classes, e.g. BaseAxisQuery expect custom XsltContext implementation to resolve namespaces prefixes (XsltContext extends XmlNamespaceManager) with respect to the NameTable, just as internal default XsltContext implementation - UndefinedXsltContext class does. The documentaion unfortunately omits that point and sample implementation in the above articles too.

The solution. Just override LookupNamespace(string prefix) method in your XsltContext implementation and pass given prefix through the NameTable:

public override string LookupNamespace(string prefix) {
    if (prefix == String.Empty)
        return String.Empty;
    string uri = base.LookupNamespace(NameTable.Get(prefix));
    if (uri == null)
        throw new XsltException("Undeclared namespace prefix - " + 
              prefix, null);
    return uri;
}
Easy, ain't it? I'm stupid spent two hours to get it.
May 29, 2003 7:01 PM | #.NET
Comments

Thank you very much.

Posted by: prakash at December 15, 2006 8:50 AM

Thank you *so* much! I was going nuts!

Posted by: Paul Hill at May 24, 2005 4:30 PM

Thank you very much. I was getting very angry with this problem. You saved my soul :-)

Posted by: at September 23, 2004 2:43 PM

Haha, awesome work dude, that just saved my ass

Posted by: Don at September 11, 2004 5:11 PM

I think u just saved me 2 hours (probably more). Thanks

Posted by: Colin at December 12, 2003 1:40 PM

Thanks Oleg, that one had me stumped as well, until I saw your solution.

Posted by: craigc at June 10, 2003 9:50 PM
Post a comment




Remember Me?

Trackback Pings

Listed below are links to weblogs that reference this post:

Implementing your own custom XsltContext objects, cont'd from public MattBerther : ISerializable
Tracked on September 24, 2003 10:25 AM