Optional use of xsl stylesheet

I have xml files that use the XSL stylesheet to format it when viewed in a web browser. I keep xml files in a central location, a shared drive that any of my colleagues can access. If they open the XML file directly from a shared location, it displays correctly, but sometimes they take a copy of the XML and only the XML file that they need. when they view the file in a browser, it cannot find the XSL stylesheet and therefore does not display. Is there a way to tell if an xsl stylesheet is available, use it, if not, just ignore the use of the stylesheet and show the xml file as if there was no stylesheet. Basically, this would mean that a local copy would not detect an error. It can be done

+4
source share
2 answers

Presumably you are relying on a <?xml-stylesheet?> Processing instruction. I don’t know how to parameterize how this happens if the stylesheet cannot be found: I dare say that it still depends on the browser.

Why not use an absolute URI that can retrieve a stylesheet from anywhere in your network? You may run into cross-site scripting problems, but it's worth a try.

0
source

I suspect there is no neat way to do this. You can use the use-when attribute when importing, for example ...

  <xsl:import xmlns:fn="http://www.w3.org/2005/xpath-functions" href="'general.xslt'" use-when="fn:unparsed-text-available( 'general.xslt') /> 

The above element imports the stylesheet "general.xslt" if it exists. The problem / limitation of this solution is that for the @href attribute, XSLT knows where to find general.xslt from your xslt configuration (OASIS directories, command line options, environment variables - whatever. It's a specific provider). However, the same location logic does not apply to unparsed-text-available (), which takes a URI parameter.

So, you may need to parameterize the above element like this ...

  <xsl:import xmlns:fn="http://www.w3.org/2005/xpath-functions" href="$stylesheet-to-import" use-when="fn:unparsed-text-available( $uri-of-stylesheet-to-import) /> 

where the following is assumed:

  • $ stylesheet-to-import is the parameter / variable for the imported style. It can be short if it can be positioned in this way by the XSLT engine, otherwise it must match $ uri-of-stylesheet-to-import
  • $ uri-of-stylesheet-to-import is the uri of the stylesheet to be imported if it exists.
  • If the file pointed to by $ uri-of-stylesheet-to-import exists, then it is a valid xslt file.

I think this solution only works for XSLT 2.0. I am not sure about XSLT 1.0.

Also read Dimitre's answer to this similar question: How do I check for an external file with XSL? .

Note: As an alternative to fn: unparsed-text-available (), you can also use fn: doc-available (). It will be slower as it checks that the document is valid XML, which may or may not be a good thing depending on your problem.

-1
source

Source: https://habr.com/ru/post/1413844/


All Articles