1

How can I turn elements that specify a flag in a bitmask to a bitmask? I have the following XML Schema:

enter image description here

How can I for example turn this XML

<Flags>
  <Flag>1</Flag>
  <Flag>3</Flag>
</Flags>

Into this output XML using XSLT?

<Bitmask>10</Bitmask>

(10 = 1010 binary - bit 1 and 3 are set)

In a procedual programming language I would simply do something like this:

var bitmask = 0;
foreach(var falg in flags) {
  bitmask = bitmask + pow(2,flag);
}

But this is not possible in xslt because the xsl:variable is static. Is there another approach, or how can this be done?

Jeldrik
  • 1,377
  • 1
  • 10
  • 35
  • XSLT 1.0 or 2.0, and if the former which XSLT processor? – Ian Roberts Apr 03 '13 at 12:08
  • XSLT 2.0 I'm using .NET XslCompiledTransform as processor: http://msdn.microsoft.com/en-us/library/system.xml.xsl.xslcompiledtransform.aspx – Jeldrik Apr 03 '13 at 12:36
  • If you're using XslCompiledTransform then it's 1.0, not 2.0. – Ian Roberts Apr 03 '13 at 12:43
  • hmm, right - I have an – Jeldrik Apr 03 '13 at 12:49
  • 1
    There may be a way to write this as a set of recursive templates in pure XSLT 1.0 but it won't be pretty, and as you say you're using .NET XslCompiledTransform it would be simpler and probably more efficient just to write an extension function with `` and do the calculation in JavaScript/C#/VB – Ian Roberts Apr 03 '13 at 12:52
  • So you can pass a nodeset to a script? I've seen this question, which sort of does the opposite thing: http://stackoverflow.com/questions/1106044/xslt-bitwise-logic there's an answer which also suggests a script block, but there are only atomar values passed to the functions. I don't know how this can be done with a nodeset. – Jeldrik Apr 03 '13 at 13:00
  • I think here it is explained how you pass a nodelist to a script function: http://support.microsoft.com/kb/330602/en-us - I will try this out and report back. - Thanks Ian, for the help! – Jeldrik Apr 03 '13 at 13:09

1 Answers1

0

This sytlesheet fragement solves the problem for the .NET XslCompiledTransform class:

<msxsl:script implements-prefix="script" language="C#">
    <![CDATA[
        public int ToBitmask(XPathNodeIterator node)
        {
            int bitmask = 0;
            while (node.MoveNext())
            {
                bitmask += Convert.ToInt32(Math.Pow(2, int.Parse(node.Current.Value)));
            }
            return bitmask;
        }
    ]]>
 </msxsl:script>
 <xsl:template match="Flags">
     <Btimask><xsl:value-of select="script:ToBitmask(Flag)"/></Btimask>
 </xsl:template>

However, I would prefere a pure XSLT solution, so that I can debug the stylesheet within XmlSpy.

Jeldrik
  • 1,377
  • 1
  • 10
  • 35