Reputation: 69
I am struggling with the following: I have a (externally provided!) XSLT which I am trying to use to display some data. The XSLT is referencing an additional other XML file which is optional. I.e. there's two XMLs involved, one of which is obviously mandatory, but the other may very well not be existing. The XSLT is referencing that XML via a variable that accesses the document with a local path:
<xsl:variable name="optionalDocument" select="document('../optionalXml.xml')"/>
In some places in the XSLT it is checked if that document exists like so:
<xsl:when test="not($optionalDocument)">
The issue I am facing now is: Any modern browser can handle this missing optional file. The console does show an error, but the XSLT is generating a valid and displayable html. Everything works as expected.
Now I am trying to build a service that does the same and transforms the XMLs using the XSLT and generates a displayable html. For that I am using C# with System.Xml.Xsl.XslCompiledTransform
which works fine if both files are available. But if the optional file is missing the transform method is throwing a FileNotFoundException which makes sense, but this actually prevents generating the expected html file.
Is there a way to make the XslCompiledTransform behave the same way as the browser in which it'll be able to handle the optional document? And if not is there a neat solution to adjust the XSLT file to only load the file if a certain parameter is set and otherwise have leave it as "null" or whatever the document($path)
function returns if the file does not exist.
Thanks for any advice!
Upvotes: 1
Views: 134
Reputation: 69
The answer by Martin was correct. I repost it to mark this question as anwsered. It is possible in the API to provide your own XmlResolver, when loading the stylesheet as well wenn calling transform like so:
xslt.Load(styleSheetPath, settings, new SilentLocalFileXmlResolver());
xslt.Transform(xmlReader, argsList, resultXmlWriter, new SilentLocalFileXmlResolver());
Note that each call gets their individual resolver which is something I have missed at first! Providing a resolver that doesn't throw the exception is sufficient. In my case I return null if the passed Uri is a file path and does not exist and otherwise redirect to the "default" XmlUrlResolver.
Upvotes: 0