C# .net 4 xslt转换扩展函数已损坏
我正在升级asp.NETV3.5Web应用程序。到v4,我在XmlDataSource对象上使用XSLT转换时遇到了一些问题 XSLT文件的一部分:C# .net 4 xslt转换扩展函数已损坏,c#,.net,asp.net,xslt,.net-4.0,C#,.net,Asp.net,Xslt,.net 4.0,我正在升级asp.NETV3.5Web应用程序。到v4,我在XmlDataSource对象上使用XSLT转换时遇到了一些问题 XSLT文件的一部分: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:HttpUtility="ds:HttpUtility"> <xsl:output method="xml" indent="yes" encoding="u
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:HttpUtility="ds:HttpUtility">
<xsl:output method="xml" indent="yes" encoding="utf-8"/>
<xsl:template match="/Menus">
<MenuItems>
<xsl:call-template name="MenuListing" />
</MenuItems>
</xsl:template>
<xsl:template name="MenuListing">
<xsl:apply-templates select="Menu" />
</xsl:template>
<xsl:template match="Menu">
<MenuItem>
<xsl:attribute name="Text">
<xsl:value-of select="HttpUtility:HtmlEncode(MenuTitle)"/>
</xsl:attribute>
<xsl:attribute name="ToolTip">
<xsl:value-of select="MenuTitle"/>
</xsl:attribute>
</MenuItem>
</xsl:template>
</xsl:stylesheet>
我一直在搜索Microsoft页面,查找v4中的任何更改,但找不到任何更改。所有这些在v3.5(以及v2之前)中都运行良好。没有收到任何错误,数据只是没有显示。问题似乎是.NET 4.0为
HttpUtility.HtmlEncode
引入了额外的重载。在.NET 3.5之前,存在以下重载:
public static string HtmlEncode(string s);
public static void HtmlEncode(string s, TextWriter output);
.NET 4.0还具有以下方法:
public static string HtmlEncode(object value);
这将导致XslTransformException
:
(方法调用不明确。扩展对象“ds:HttpUtility”包含多个具有1个参数的“HtmlEncode”方法
您可能看不到异常,因为它在某个地方被捕获,并且没有立即报告
使用.NET Framework类作为扩展对象是一件脆弱的事情,因为新的框架版本可能会破坏您的转换
修复方法是创建自定义包装类并将其用作扩展对象。此包装类可能没有具有相同数量参数的重载:
class ExtensionObject
{
public string HtmlEncode(string input)
{
return System.Web.HttpUtility.HtmlEncode(input);
}
}
//...
XsltArgumentList arguments = new XsltArgumentList();
arguments.AddExtensionObject("my:HttpUtility", new ExtensionObject());
您要编码的
MenuTitle
的字符串值是多少?
public static string HtmlEncode(object value);
class ExtensionObject
{
public string HtmlEncode(string input)
{
return System.Web.HttpUtility.HtmlEncode(input);
}
}
//...
XsltArgumentList arguments = new XsltArgumentList();
arguments.AddExtensionObject("my:HttpUtility", new ExtensionObject());