日期:2010-07-25  浏览次数:20415 次

想要一个正则表达式的匹配函数,但是XPath1.0中间没有,
只好自己扩展一个,在网上搜了一下,有一篇文章不错,
http://www.microsoft.com/china/MSDN/library/data/xml/AddingCustomFunctionstoXpath.mspx?mfr=true
该文章定义了一个split,一个replace,不过就是没有match,
只好在它的基础上,扩展一下

仔细观察一下代码,发现想要扩展一个函数很简单,只要修改这几段就好了:

1:CustomContext.cs


// Function to resolve references to my custom functions.
        public override IXsltContextFunction ResolveFunction(string prefix,
     string name, XPathResultType[] ArgTypes)
        {
            XPathRegExExtensionFunction func = null;
            // Create an instance of appropriate extension function class.
            switch (name)
            {
                case "Match":
                    // Usage
                    // myFunctions:Matches(string source, string Regex_pattern) returns Boolean
                    func = new XPathRegExExtensionFunction("Match", 2, 2, new
        XPathResultType[] {XPathResultType.String, XPathResultType.String}
        , XPathResultType.Boolean );
                    break;
                case "Split":
                    // Usage
                    // myFunctions:Split(string source, string Regex_pattern, int n) returns string
                    func = new XPathRegExExtensionFunction("Split", 3, 3, new
        XPathResultType[] {XPathResultType.String, XPathResultType.String,
XPathResultType.Number}, XPathResultType.String);
                    break;
                case "Replace":
                    // Usage
                    // myFunctions:Replace(string source, string Regex_pattern, string replacement_string) returns string
                    func = new XPathRegExExtensionFunction("Replace", 3, 3, new
        XPathResultType[] {XPathResultType.String, XPathResultType.String,
XPathResultType.String}, XPathResultType.String);
                    break;
            }