XPathExpressionインスタンスでXPath関数をプログラムで使用する方法
-
03-07-2019 - |
質問
現在のプログラムでは、XmlDocumentに適用するXPathExpressionインスタンスをプログラムで作成する必要があります。 xpathでは、「ends-with」などのXPath関数を使用する必要があります。ただし、「ends-with」を使用する方法が見つかりません。 XPathで。私
以下のような例外をスローします
未処理の例外: System.Xml.XPath.XPathException: Namespace ManagerまたはXsltC ontext 必要です。このクエリにはプレフィックスがあり、 変数、またはユーザー定義関数。
で MS.Internal.Xml.XPath.CompiledXpathExpr.get_QueryTree() で System.Xml.XPath.XPathNavigator.Evaluate(XPathExpression expr、XPathNodeIt eratorコンテキスト)
で System.Xml.XPath.XPathNavigator.Evaluate(XPathExpression expr)
コードは次のようなものです:
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 コンテキスト)at MS.Internal.Xml.XPath.CompiledXpathExpr.SetContext(XmlNamespaceManager nsM anager)で System.Xml.XPath.XPathExpression.Compile(String xpath、IXmlNamespaceResolver nsResolver)
XPathExpression.Compileで既製のXPath関数を使用するコツを知っている人はいますか? ありがとう
解決
関数 < code> ends-with() XPath 1.0 ただし XPath 2.0 のみ XQuery 。
.NETを使用しています。 。この日のNETは実装していません XPath 2.0 、 XSLT 2.0 または XQuery 。
XPath 1.0式を簡単に構築でき、その評価により関数 ends-with()
と同じ結果が生成されます:
$ 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
)