如何在XSLT 3.0中调用自定义.NET代码及DLL?求示例
在XSLT 3.0中调用自定义C#代码(含DLL)的实现示例
XSLT 3.0不再支持msxsl:script这类微软XSLT 1.0私有扩展,要调用C#代码需依赖XSLT处理器的扩展机制(主流方案是使用Saxon.NET,这是.NET生态中支持XSLT 3.0的成熟处理器)。以下是两种常见场景的简单示例:
一、准备自定义C#逻辑(类/DLL)
先编写包含所需功能的C#类,既可以直接嵌入项目,也可以编译为独立DLL复用。
示例C#类
using System; namespace XsltCustomTools { public class CustomFunctions { // 实现原示例中的日期格式化功能 public string GetFormattedCurrentDateTime() { DateTime dt = DateTime.Now; string datePart = dt.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); string timePart = dt.ToString("T", System.Globalization.CultureInfo.InvariantCulture); return $"{datePart}T{timePart}"; } // 可添加更多自定义方法 public string ToUpperCase(string input) { return input?.ToUpperInvariant() ?? string.Empty; } } }
编译为DLL(可选)
如果要复用这个类,用命令行编译为DLL:
csc /target:library CustomFunctions.cs
生成XsltCustomTools.dll文件。
二、在XSLT 3.0中调用C#逻辑
以Saxon.NET为例,需要先通过NuGet安装Saxon-HE包(免费版),然后分两步:在.NET代码中注册扩展对象,在XSLT中调用对应方法。
1. .NET代码中注册扩展对象
using Saxon.Api; using XsltCustomTools; class Program { static void Main() { // 初始化Saxon处理器 Processor xsltProcessor = new Processor(); XsltCompiler compiler = xsltProcessor.NewXsltCompiler(); // 加载XSLT文件 XsltExecutable executable = compiler.Compile(new Uri("transform.xsl")); XsltTransformer transformer = executable.Load(); // 实例化自定义C#类,并绑定到XSLT的命名空间 CustomFunctions customTools = new CustomFunctions(); transformer.SetExtensionFunction( new QName("http://your-namespace.com/custom-functions", "custom"), customTools ); // 设置输入XML和输出目标 XdmNode inputXml = xsltProcessor.NewDocumentBuilder().Build(new Uri("input.xml")); transformer.InitialContextNode = inputXml; using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create("output.xml")) { transformer.Run(new XmlDestination(writer)); } } }
2. 对应的XSLT 3.0文件(transform.xsl)
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:custom="http://your-namespace.com/custom-functions" exclude-result-prefixes="custom"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <result> <!-- 调用自定义日期格式化方法 --> <formatted-date-time> <xsl:value-of select="custom:GetFormattedCurrentDateTime()"/> </formatted-date-time> <!-- 调用字符串转大写方法 --> <uppercase-demo> <xsl:value-of select="custom:ToUpperCase('hello xslt 3.0')"/> </uppercase-demo> </result> </xsl:template> </xsl:stylesheet>
关键说明
- 命名空间要保持一致:XSLT中声明的
custom命名空间,必须和.NET代码中QName指定的命名空间完全匹配。 - 如果使用已编译的DLL,只需在.NET项目中引用该DLL,无需修改代码逻辑。
- 微软原生的
XslCompiledTransform仅支持XSLT 1.0,若要使用XSLT 3.0特性,优先选择Saxon.NET。
内容的提问来源于stack exchange,提问作者Xav Sc
相关产品推荐
相关产品推荐

