想要一個正規表示式的符合函數,但是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;
}
return func;
}
2: XPathRegExExtensionFunction.cs
// This method is invoked at run time to execute the user defined function.
public object Invoke(XsltContext xsltContext, object[] args,
XPathNavigator docContext)
{
Regex r;
string str = null;
// The two custom XPath extension functions
switch (m_FunctionName)
{
case "Match":
r = new Regex(args[1].ToString());
MatchCollection m = r.Matches(args[0].ToString());
if (m.Count == 0)
{
return false;
}
else
{
return true;
}
break;
case "Split":
r = new Regex(args[1].ToString());
string[] s1 = r.Split(args[0].ToString());
int n = Convert.ToInt32(args[2]);
if (s1.Length < n)
str = "";
else
str = s1[n - 1];
break;
case "Replace":
r = new Regex(args[1].ToString());
string s2 = r.Replace(args[0].ToString(), args[2].ToString());
str = s2;
break;
}
return (object)str;
}
另外一個檔案XPathExtensionVariable.cs其實跟函數擴充沒有太多的關係,那是設定參數的。
這連個檔案修改好了之後,就可以呼叫了:
query = navigator.Compile("xdUtil:Match(9,'\d')");
CustomContext cntxt = new CustomContext();
// Add a namespace definition for myFunctions prefix.
cntxt.AddNamespace("xdUtil", " http://myXPathExtensionFunctions ");
query.SetContext(cntxt);
Evaluate(query, navigator);
當然,要是支援XPath2.0 就好了,XPath2.0這些函數都是內建支援的,可惜目前好像還不支援。
全部的程式碼在這裡: