我创建了一个标准的 XsltContext 类并按如下方式调用它:
XPathCustomContext context = new XPathCustomContext(new NameTable());
context.AddNamespace("windward", XPathCustomContext.Namespace);
XsltArgumentList varList = new XsltArgumentList();
varList.AddParam("stat-index", "", 0);
context.ArgList = varList;
XmlDocument doc = new XmlDocument();
doc.Load("c:\\test\\order.xml");
object xx = doc.CreateNavigator().Evaluate("/order[1]/customer[1]/num[@negone = $stat-index]", context);
在 .net 4.0 下运行时它工作正常。但是在 .NET 3.5(我们目前必须使用)下,我得到:
System.Xml.XPath.XPathException was unhandled
Message=XsltContext is needed for this query because of an unknown function.
Source=System.Xml
StackTrace:
at MS.Internal.Xml.XPath.CompiledXpathExpr.UndefinedXsltContext.ResolveVariable(String prefix, String name)
at MS.Internal.Xml.XPath.VariableQuery.SetXsltContext(XsltContext context)
at MS.Internal.Xml.XPath.LogicalExpr.SetXsltContext(XsltContext context)
at MS.Internal.Xml.XPath.FilterQuery.SetXsltContext(XsltContext input)
at MS.Internal.Xml.XPath.CompiledXpathExpr.SetContext(XmlNamespaceManager nsManager)
at System.Xml.XPath.XPathExpression.Compile(String xpath, IXmlNamespaceResolver nsResolver)
at System.Xml.XPath.XPathNavigator.Evaluate(String xpath, IXmlNamespaceResolver resolver)
at CustomXpathFunctions.Program.Main(String[] args) in c:\src\CustomXpathFunctions\Program.cs:line 62
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
知道为什么吗?
示例代码位于 http://www.windwardreports.com/temp/CustomXPathFunctionsBug.zip
谢谢 - 戴夫
最佳答案
想出了一个办法来做到这一点。使用像这样的 XPathExpression:
XPathNavigator nav = doc.CreateNavigator();
XPathExpression exp = nav.Compile("/order[1]/customer[1]/num[@negone = $stat]");
exp.SetContext(ctx);
object zzz = nav.Evaluate(exp);
至于为什么 - 我的猜测是 Evaluate(string, context) 仅在 .NET 3.5 中将它用于 namespace ,而 XPathExpression 将它用于所有内容。不过,关键是这行得通。
ps - 请对这个答案中的鼻涕点赞 - 这真的很难弄清楚。
关于c# - XPath 扩展方法在 .NET 3.5 中失败,在 .NET 4.0 中有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6528630/