问题
I`m having problem with my XSLT - Transformation. This is how I create XSLT class
XmlUrlResolver resolver = new XmlUrlResolver();
resolver.Credentials = CredentialCache.DefaultCredentials;
var xslt = new XslTransform();
xslt.Load(_xslPath, resolver);
using (StringReader sr = new StringReader(myXml))
{
XPathDocument doc = new XPathDocument(sr);
using (var sw = new StringWriter())
{
var argList = new XsltArgumentList();
var doc2 = File.ReadAllText("D:\\test\\Doc2.xml");
using (StringReader sr2 = new StringReader(doc2))
{
XPathDocument doc2XPath = new XPathDocument(sr2);
argList.AddParam("doc2", "", doc2XPath);
xslt.Transform(doc, argList, sw);
}
}
}
In XSLT I have call like:
<xsl:call-template name="docBody">
<xsl:with-param name="doc" select="$doc2/myDoc"/>
<xsl:with-param name="docNr" select="$doc2Nr"/>
</xsl:call-template>
When XSLT calls Transform it gives me:
System.Xml.XPath.XPathException: 'Expression must evaluate to a node-set.'
How I can pass another XML as parameter to make it work using only XslTransform
?
回答1:
Looking at https://docs.microsoft.com/en-us/dotnet/standard/data/xml/xsltargumentlist-for-style-sheet-parameters-and-extension-objects?view=netframework-4.8#xslt-style-sheet-parameters, the only .NET type to be seen by XslTransform
as an XSLT/XPath node-set is an XPathNodeIterator
so one way to pass your XPathDocument
in would be to use doc2XPath.CreateNavigator().Select("/")
as the argument to the AddParam
method.
Note also that you can pass in URLs to XSLT and then simply use the XSLT document
function to load a document.
I think XslCompiledTransform is a bit more flexible (https://docs.microsoft.com/en-us/dotnet/standard/data/xml/xslt-parameters?view=netframework-4.8) when it comes to passing XPathDocument
s directly.
来源:https://stackoverflow.com/questions/59699403/xslttransform-system-xml-xpath-xpathexception-expression-must-evaluate-to-a-no