.NET 4.8中使用XPath2.0的string-join和distinct-values报异常求助
.NET 4.8中XPath2.net库调用XPath2.0函数报错的解决方法
问题场景
在.NET 4.8环境下,使用XPath2.net库执行包含fn:string-join、fn:distinct-values的XPath2.0表达式时,已添加fn命名空间(http://www.w3.org/2005/xpath-functions),编译表达式无错误,但调用Select或Evaluate时始终抛出异常:
System.Xml.XPath.XPathException: 'Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.'
核心原因
默认的XPathNavigator和XPathExpression仅支持XPath1.0,无法识别XPath2.0扩展函数。必须使用XPath2.net库提供的专属类型来处理XPath2.0语法,同时确保命名空间上下文被正确关联。
解决步骤
- 替换导航器类型:将默认
XPathNavigator替换为XPath2Navigator,它是XPath2.net库对XPath2.0特性的实现载体。 - 使用XPath2专属编译方法:用
XPath2Expression.Compile编译表达式,编译时传入命名空间管理器,确保函数前缀能被正确解析。 - 调用XPath2导航器的方法:使用
XPath2Navigator的Evaluate或Select方法执行表达式,而非默认导航器的方法。
修正后的完整代码
using System.Diagnostics; using System.Xml; using System.Xml.XPath; using XPath2; // 需引入XPath2.net库的命名空间 namespace ConsoleApp4 { internal class Program { static void Main(string[] args) { var xPathDoc = new XPathDocument(@"abc.xml"); // 替换为XPath2Navigator var nav = XPath2Navigator.Create(xPathDoc.CreateNavigator()); var xmlnsManager = new XmlNamespaceManager(nav.NameTable); xmlnsManager.AddNamespace("fn", "http://www.w3.org/2005/xpath-functions"); var xPath = "fn:string-join(fn:distinct-values(//MyType/MyTypeNumber/alternatives/MyTypeNumber/value),',')"; // 使用XPath2Expression编译,传入命名空间管理器 var exp = XPath2Expression.Compile(xPath, xmlnsManager); // 执行表达式并输出结果 var value = nav.Evaluate(exp); Debug.WriteLine(value.ToString()); } } }
额外说明
- 若XML中存在自定义命名空间,需在
XmlNamespaceManager中一并添加,否则节点路径会匹配失败。 - 无需在XPath表达式中强制添加
fn:前缀,XPath2.net库默认会识别无前缀的XPath2.0标准函数,比如直接写string-join(distinct-values(...), ',')也可正常执行。
内容的提问来源于stack exchange,提问作者Thierry
相关产品推荐
相关产品推荐

