Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Environment Variables in an XSLT Stylesheet with Saxon

Tags:

xslt

saxon

I'm trying to generate an XML file with the my machine's hostname in some arbitrary element or attribute, e.g.

<hostname>myHostname</hostname>

I'm using Saxon 9.2. I can think of three ways to do this:

  1. Read and parse /etc/sysconfig/network (I'm using Fedora)
  2. Read the environment variable (as in $ echo $HOSTNAME)
  3. Pass the hostname to saxon and then use somehow dereference a variable (not sure if this is possible)

Are any of these possible? I think the first option is most likely to work, but I think the other two options will produce less verbose XSLT.

I also have a related question:

Currently, I have an XSLT and source XML file that generates a bunch of XML files, it works like I expect it to. Is there anyway I can selectively generate one file per host? That is, I want to say 'if the hostname is myHostName then generate the XML file for myHostName, if the hostname is myOtherHostName then generate the XML file for myOtherHostName'.

I ask this because I'm trying to configure a large number of machines and if I could drop an XSLT and XML file on each and then call the same command on every machine and hten get the right XML on each it would be really convienent.

like image 986
devin Avatar asked Nov 01 '25 00:11

devin


2 Answers

You should pass a parameter to your xslt when "calling" it. I think this is the most robust solution.

So at the top of your stylesheet you would have something like :

<xsl:param name="hostName"/>

Then you can use it in your .xslt via the usual notation : $hostName etc.

You just then need to pass those parameters when calling the xslt processor. Depending on how you use it this may vary.

like image 93
FailedDev Avatar answered Nov 03 '25 04:11

FailedDev


You can generate an XML file containing all needed parameters, then you can either pass it as parameter to the transformation (refer to the code samples to see examples of how this is done with Saxon).

Here is a link that can help: https://www.saxonica.com/html/documentation/javadoc/net/sf/saxon/expr/instruct/GlobalParameterSet.html

Or simpler, save this XML file in the file system and just pass as parameter to the transformation the file path and name.

Then inside the transformation, use the standard XSLT function document() to load the XML document that contains the parameters.

Even further simplification is possible, if this file can be stored at a location that has exactly the same path on all machines. Then this avoids the need to pass this filepath as parameter to the transformation.

like image 37
Dimitre Novatchev Avatar answered Nov 03 '25 06:11

Dimitre Novatchev