Question

I'm having difficulties getting XslCompiledTransform.Load method to take a server path. I googled around and found that I need to do something like:

xslt.Load(System.Web.HttpContext.Server.MapPath(xslPath),
           XsltSettings.Default, new XmlUrlResolver());

But it returned an error saying HttpContext is null.

I also tried:

xslt.Load(System.Web.HttpServerUtility.MapPath(xslPath), 
           XsltSettings.Default, new XmlUrlResolver());

That also returned an error saying an object reference is required for the non-static field, method, or property System.Web.HttpServerUtility.MapPath(string)

The xslPath has a path that points to a xsl file in Sharepoint Web. I just want XslCompiledTransform to load the xsl file with the server path. Is it possible? If so, what is the proper way or hackish way of doing it?

EDIT: I have access to a SPWeb object which contains the path to the xsl file. However when I check the ServerRelativeUrl, it just says "/MyTree/xsl.xsl". The problem here is I couldn't get the XslCompiledTransform.Load to load the file from SharePoint list.

Thanks.

Was it helpful?

Solution 2

What I found in the end is that if I pass in a url that does not resemble a local path, the XslCompiledTransform class will automatically switch to a different mode to read the path as a URL.

If I pass in a string that contains only the name of the file, XslCompiledTransform will look for the file in my local hard disk. Likewise if I pass in something like /myFolder/myXsl.xsl.

However, if I pass in a sharepoint URL e.g. web.ParentWeb.Url + NameOfFile, then it'll go off to read it from the Sharepoint URL.

I'm not 100% sure why it does the automatic switch, but at least the above worked for me.

OTHER TIPS

During a the processing of a request, the current HttpContext is HttpContext.Current. In a Page/UserControl/WebPart this is also the property Context.

HttpContext.Context.Server.MapPath(xslPath)

If your method is not called during the processing of a request, HttpContext.Current will be null. In this case you could map the path manually.

public string MapPath(string path)
{
    if (HttpContext.Current != null)
        return HttpContext.Current.Server.MapPath(path);

    path = path.Replace("/", @"\");
    if (path.StartsWith(@"~\")) {
        path = path.Substring( 2 );
    } else if (path.StartsWith(@"\")) {
        path = path.Substring( 1 );
    }
    // a non-prefixed path is already relative to your web server root

    return Path.Combine( HttpRuntime.AppDomainAppPath, path );
}

The above is for mapping disk paths in ASP.NET in general.

If the file is contained in you SPWeb object, you should use SPWeb.GetFile

SpWeb web;

SPFile file = web.GetFile( path );

XmlReader r = XmlReader.Create( file.OpenBinaryStream() );
xslt.Load( r );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top