XsltTransform System.Xml.XPath.XPathException: 'Expression must evaluate to a node-set.'

狂风中的少年 提交于 2020-02-06 07:50:34

问题


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 XPathDocuments directly.



来源:https://stackoverflow.com/questions/59699403/xslttransform-system-xml-xpath-xpathexception-expression-must-evaluate-to-a-no

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!