xslt作为扩展标记语言,其自身系统函数有限,远远满足不了我们的需求,要用xslt处理xml,必须要对数据做些处理(如果可以,我还是不会选择xslt)。
今天就用xslt来处理文本中html标记为例,来讲讲如何利用xslt来执行自定义函数。
我们来看看利用这个xml文本生成报表:
View Code
现在客户要求在生成的报表中没有html标记,即是不能用disable-output-escaping="yes"来直接执行html标记,或许要说可以用xslt系统函数translate()来做字符匹配,但是我们要匹配的标记何其之多,而且很多标记未知,对于translate()来说又不支持正则,所以我觉得用xslt来写自定义函数来执行replace将html替换为空。
要使用xslt自定义函数,我们必须要引用函数命名空间:
下面要定义自定义函数就可以用我们指定的工具前缀来定义(必须指明implements-prefix=我们自定义的前缀名)
View Code
//javascript function
// C# Function
// VB Function
]]>
// C# Function
// VB Function]]>
有了这些基础知识我们就可以来写我们自定义的函数来去掉文本中的html标记了,先来看看我们的C#函数:
View Code
// C# Function
public static string NoHTML(string Htmlstring)
{
Htmlstring = Regex.Replace(Htmlstring, @"]*>", "", RegexOptions.IgnoreCase);
return Htmlstring;
}
]]>
public static string NoHTML(string Htmlstring)
{
Htmlstring = Regex.Replace(Htmlstring, @"]*>", "", RegexOptions.IgnoreCase);
return Htmlstring;
}]]>
VB函数:
View Code
Function ReplaceBreakLineInExcelChar(str)
Dim pattern As String = ""
Dim regex As New Regex(pattern)
str = regex.Replace(str, "")
ReplaceBreakLineInExcelChar=str
End Function
]]>
Dim pattern As String = ""
Dim regex As New Regex(pattern)
str = regex.Replace(str, "")
ReplaceBreakLineInExcelChar=str
End Function]]>
javascript函数:
View Code
function replaceHTML(str)
{
return str.replace(/].*?>/g,'');
}
]]>
{
return str.replace(/].*?>/g,'');
}]]>
函数现在写好了,我们来看看这三种函数分别是怎么调用的:
最后要注意的是在调用vb和javascript函数的时候,一定要注意参数类型转换,如果不转换默认传递的是 XPathArrayIterator 对象。所以我们在传递前用string()函数处理下。