Question

I'm running into a bit of a pickle where I'm working out network masks into shorthand (ie. 255.255.255.0 = /24)

I did a whole bunch of googling, and weirdly enough, no one has ever asked how to compute this in XSL.

So I came up with my own solution: why not do a whole bunch of statements like:

<xsl:choose>
    <xsl:when test="'255.255.255.0'">
        <xsl:value-of select="'/24'"/>
    </xsl:when>
    <xsl:when test="'255.255.0.0'">
        <xsl:value-of select="'/16'"/>
    </xsl:when>
    ...

and so on and so forth. Then I realized. I think I'm thinking too much outside the box. There has to be a solution to calculate this. There are too many possibilities of a network mask. Does anyone know how to calculate it?

Was it helpful?

Solution

Theoretically, it is possible, but its probably going to require extraordinarily verbose code, especially in XSLT1.0.

Network masks rely heavily on bitwise logic, which this answer covers in XSLT. But not only that, you'll need to tokenize the string first, which isn't easy/short in XSLT 1.0.

Then you need to verify that each octet is correct (i.e. consecutive 1's followed by consecutive 0s).

In all, it might just be shorter code-wise to list the 31 cases, and check against those in its own little named template somewhere. Possibly even computationally quicker, since string tokenization would be recursive, as would the bit logic.

OTHER TIPS

Another alternative would be to step outside XSLT and write, and plug in, an extension function. In fact if there's an existing Java static function which will do this, some XSLT processors (eg Apache Xalan) will let you invoke it fairly directly. That does mean giving up some portability since you need to make sure the same extension will be available everywhere you run the stylesheet, but sometimes it is the best solution.

Unfortunately I don't think the standardized ESXLT extension functions include something for this purpose.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top