它会像下面那样抛出异常
Unhandled Exception:
System.Xml.XPath.XPathException:
Namespace Manager or XsltC ontext
needed. This query has a prefix,
variable,or user-defined function.
at
MS.Internal.Xml.XPath.CompiledXpathExpr.get_QueryTree()
at
System.Xml.XPath.XPathNavigator.Evaluate(XPathExpression
expr,XPathNodeIt erator context)
at
System.Xml.XPath.XPathNavigator.Evaluate(XPathExpression
expr)
代码如下:
XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8"" ?> <myXml xmlns=""http://MyNamespace"" xmlns:fn=""http://www.w3.org/2005/xpath-functions""> <data>Hello World</data> </myXml>"); XPathNavigator navigator = xdoc.CreateNavigator(); XPathExpression xpr; xpr = XPathExpression.Compile("fn:ends-with(/myXml/data,'World')"); object result = navigator.Evaluate(xpr); Console.WriteLine(result);
在编译表达式时,我尝试更改代码以插入XmlNamespaceManager,如下所示
XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8"" ?> <myXml xmlns=""http://MyNamespace"" xmlns:fn=""http://www.w3.org/2005/xpath-functions""> <data>Hello World</data> </myXml>"); XPathNavigator navigator = xdoc.CreateNavigator(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(xdoc.NaMetable); nsmgr.AddNamespace("fn","http://www.w3.org/2005/xpath-functions"); XPathExpression xpr; xpr = XPathExpression.Compile("fn:ends-with(/myXml/data,'World')",nsmgr); object result = navigator.Evaluate(xpr); Console.WriteLine(result);
它在XPathExpression.Compile调用失败:
Unhandled Exception:
System.Xml.XPath.XPathException:
XsltContext is needed for this query
because of an unknown function. at
MS.Internal.Xml.XPath.CompiledXpathExpr.UndefinedXsltContext.ResolveFuncti
on(String prefix,String name,
XPathResultType[] ArgTypes) at
MS.Internal.Xml.XPath.FunctionQuery.SetXsltContext(XsltContext
context) at
MS.Internal.Xml.XPath.CompiledXpathExpr.SetContext(XmlNamespaceManager
nsM anager) at
System.Xml.XPath.XPathExpression.Compile(String
xpath,IXmlNamespaceResolv er
nsResolver)
任何人都知道用XPathExpression.Compile使用现成的XPath函数的技巧?
谢谢
解决方法
ends-with()
未为
XPath 1.0定义,但仅针对
XPath 2.0和
XQuery.
你在使用.NET. .NET在此日期不实现XPath 2.0,XSLT 2.0或XQuery.
可以轻松构建XPath 1.0表达式,其评估产生与函数ends-with()相同的结果:
$str2 = substring($str1,string-length($str1) – string-length($str2)1)
生成相同的布尔结果(true()或false())为:
($str1,$str2)
在具体情况下,您只需要替换$str1和$str2的正确表达式.相应地,它们是/ myXml / data和’World’.
所以,XPath 1.0表达式使用,相当于XPath 2.0表达式(/ myXml / data,’World’)是:
'World' = substring(/myXml/data,string-length(/myXml/data) - string-length('World') +1 )