我当前的程序需要以编程方式使用创建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) 知道我不能使用HTMLAgilityPack,只能使用直接的.NET,比如我有一个字符串,其中包含一些我需要以这种方式解析和编辑的HTML:
.net中是否有可用的方法?