如何以编程方式在XPathExpression实例中使用XPath函数?

我当前的程序需要以编程方式使用创建XPathExpression实例来应用于XmlDocument。 xpath需要使用一些XPath函数,如“ends-with”。 但是,我找不到在XPath中使用“ends-with”的方法。 一世

它抛出exception如下

未处理的exception:System.Xml.XPath.XPathException:需要命名空间管理器或XsltC ontext。 此查询具有前缀,变量或用户定义的函数。
System.Xml.XPath.XPathNavigator.Evaluate(XPathExpression expr,XPathNodeIt erator context)中的MS.Internal.Xml.XPath.CompiledXpathExpr.get_QueryTree()
在System.Xml.XPath.XPathNavigator.Evaluate(XPathExpression expr)

代码是这样的:

XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(@"  Hello World "); 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(@"  Hello World "); 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调用时失败:

未处理的exception:System.Xml.XPath.XPathException:由于函数未知,此查询需要XsltContext。 在MS.Internal.Xml上的MS.Internal.Xml.XPath.CompiledXpathExpr.UndefinedXsltContext.ResolveFuncti上(字符串前缀,字符串名称,XPathResultType [] ArgTypes)位于MS.Internal.Xml的MS.Internal.Xml.XPath.FunctionQuery.SetXsltContext(XsltContext上下文)。 System.Xml.XPath.XPathExpression.Compile上的XPath.CompiledXpathExpr.SetContext(XmlNamespaceManager nsM anager)(String xpath,IXmlNamespaceResolv er nsResolver)

有人知道使用XPathExpression.Compile的现成XPath函数的技巧吗? 谢谢

函数 ends-with() 没有为XPath 1.0定义, 但仅适用于XPath 2.0和XQuery 。

您正在使用.NET。 。 这个日期的.NET没有实现 XPath 2.0XSLT 2.0XQuery

可以很容易地构造一个XPath 1.0表达式,其评估产生与函数ends-with()相同的结果:

$str2 = substring($str1, string-length($str1)- string-length($str2) +1)

产生相同的布尔结果( true()false() )如下:

ends-with($str1, $str2)

在具体情况下,您只需要为$str1$str2替换正确的表达式。 因此,它们是/myXml/data'World'

因此,要使用的XPath 1.0表达式,相当于XPath 2.0表达式的ends-with(/myXml/data, 'World')

 'World' = substring(/myXml/data, string-length(/myXml/data) - string-length('World') +1 )