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

Mor*_*eng 10 c# xml xpath namespaces

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

它抛出异常如下

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

代码是这样的:

    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);
Run Code Online (Sandbox Code Playgroud)

我试图在编译表达式时更改代码以插入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);
Run Code Online (Sandbox Code Playgroud)

它在XPathExpression.Compile调用时失败:

未处理的异常: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函数的技巧吗?谢谢

Dim*_*hev 34

该函数 未针对XPath 1.0定义,仅针对XPath 2.0XQuery.ends-with()

您正在使用.NET..这个日期的.NET没有实现 XPath 2.0,XSLT 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表达式来使用,也就是等同于2.0的XPath表达式ends-with(/myXml/data, 'World'):

'World' = 
   substring(/myXml/data,
             string-length(/myXml/data) - string-length('World') +1
             )
Run Code Online (Sandbox Code Playgroud)