XPathExpression 인스턴스에서 XPath 함수를 프로그래밍 방식으로 사용하는 방법은 무엇입니까?
-
03-07-2019 - |
문제
현재 프로그램은 XMLDocument에 적용하려면 XPathExpression 인스턴스를 프로그래밍 방식으로 만들어야합니다. XPath는 "ENDS-WITH"와 같은 일부 XPATH 기능을 사용해야합니다. 그러나 XPath에서 "Ends-With"를 사용하는 방법을 찾을 수 없습니다. 나
아래와 같이 예외를 던집니다
처리되지 않은 예외 : System.xml.xpath.xpathException : 네임 스페이스 관리자 또는 XSLTC Ontext가 필요합니다. 이 쿼리에는 접두사, 가변 또는 사용자 정의 기능이 있습니다.
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)
코드는 다음과 같습니다.
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.com에서 실패합니다.
처리되지 않은 예외 : system.xml.xpath.xpathexception : 알 수없는 함수로 인해이 쿼리에는 xsltcontext가 필요합니다. ms.internal.xml.xpath.compiledxpathexpr.undefinedxsltcontext.resolvefuncti on (문자열 접두사, 문자열 이름, xpathresulttype [] argtypes) at ms.internal.xpath.xpath.functurey.setxsltcontxt (xsltcontext) at ms.internal.xml. xpath.compiledxpathexpr.setcontext (xmlnamespacemanager nsm anager) at system.xml.xpath.xpathexpression.compile (String xpath, ixmlnamespaceresolv er nsresolver)
XPathExpression.comPile과 함께 기성품 XPath 기능을 사용하는 트릭을 아는 사람이 있습니까? 감사
해결책
함수 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
)