4

对于一个 ASP.NET 项目,我编写了一个控制器操作和一个表单,用户可以在其中输入 xpath 表达式并从服务器上的 xml 文件中检索结果。它工作正常,即使使用一些字符串函数,如 concat、substring-before 和 substring-after。

为了去掉输出中的一些逗号,我尝试使用字符串连接和标记化。但是,通过使用其中一个函数,我最终会遇到 XPathException。

XPathDocument doc = new XPathDocument(@"C:\temp.xml");
XPathNavigator navigator = doc.CreateNavigator();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(navigator.NameTable);
nsmgr.AddNamespace("x", "systemInfo");
var temp = navigator.Evaluate("string-join(tokenize('The quick brown fox', ' '), ';')", nsmgr); // Exception

我没有正确使用这些 xpath 函数吗?

4

2 回答 2

2

string-join并且tokenize是 XPath 2.0 的功能,但 .net 的 XPathNavigator 仅支持 XPath 1.0。您不能使用这些函数,并且没有与它们等效的 XPath 1.0。

在 C# 中执行 XPath 之外的字符串操作或使用一些扩展功能的库,您可能想看看SaxonBaseX,它们都为 C# 提供 API。还有更多的,包括开源的和商业的。

针对这个特定示例的 XPath 1.0 hack:translate('The quick brown fox', ' ', ';')将用分号替换所有出现的空格。

于 2014-02-19T15:46:46.823 回答
2

您需要研究第三方解决方案,例如 Saxon 9 的 .NET 版本或 XmlPrime。XmlPrime 的 API 接近于最初的 Microsoft API,请参阅http://www.xmlprime.com/xmlprime/doc/2.9/T_XmlPrime_ExtensionMethods_XPathNavigatorExtensions.htm,其中添加了扩展方法以允许 XPath 2.0 评估。

于 2014-02-19T15:52:21.543 回答