My current program need to use programatically create a XPathExpression instance to apply to XmlDocument. The xpath needs to use some XPath functions like "ends-with". However, I cannot find a way to use "ends-with" in XPath. I
It throw exception like below
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)
The code is like this:
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);
I tried to change the code to insert XmlNamespaceManager when compiling the expression, like below
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);
It fails on XPathExpression.Compile invocation:
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)
Anybody know the trick to use off-the-shelf XPath functions with XPathExpression.Compile? Thanks