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

如下所示抛出异常

  

未处理的例外情况:   System.Xml.XPath.XPathException:   命名空间管理器或XsltC ontext   需要。这个查询有一个前缀,   变量或用户定义的函数。
  在   MS.Internal.Xml.XPath.CompiledXpathExpr.get_QueryTree()   在   System.Xml.XPath.XPathNavigator.Evaluate(XPathExpression   expr,XPathNodeIt erator context)
  在   System.Xml.XPath.XPathNavigator.Evaluate(XPathExpression   表达式)

代码是这样的:

    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调用失败:

  

未处理的例外情况:   System.Xml.XPath.XPathException:   此查询需要XsltContext   因为功能未知。在   MS.Internal.Xml.XPath.CompiledXpathExpr.UndefinedXsltContext.ResolveFuncti   on(字符串前缀,字符串名称,   XPathResultType [] ArgTypes)at   MS.Internal.Xml.XPath.FunctionQuery.SetXsltContext(XsltContext   上下文)   MS.Internal.Xml.XPath.CompiledXpathExpr.SetContext(的XmlNamespaceManager   nsM anager)at   System.Xml.XPath.XPathExpression.Compile(字符串   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表达式,其评估结果与函数 结束时产生相同的结果 - ()

$ 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
             )
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top