Search code examples
xmlapache-flexxsltair

Performing XML Transformations in Flex


I'd like to be able to run an xml transformation using an xslt file in my AIR project. What's the best way to accomplish this?


Solution

  • In AIR 1.5, a version of Webkit with support for XSLT is included.

    Use the class XSLTProcessor from JavaScript just like you would in Firefox. (Note: There is one annoying bug. Stylesheets cannot contain non-breaking spaces, no matter whether literally or as a character reference. I am told that more recent versions of Webkit will fix this issue.)

    Below is a complete example.

    Create a file test.html

    <html>
      <head>
        <title>XSLT test</title>
        <script type="text/javascript">
          // <!--
          function test() {
    
            // Step 1: Parse the stylesheet
            var stylesheet
              = "<xsl:transform xmlns:xsl='http://www.w3.org/1999/XSL/Transform'"
              + "               version='1.0'>"
              + "  <xsl:template match='/'>"
              + "    Hello World from XSLT!"
              + "  </xsl:template>"
              + "</xsl:transform>";
            var stylesheetDocument
              = new DOMParser().parseFromString(stylesheet, "application/xml");
    
            // Step 2: Parse the source document
            var source = "<dummy/>";
            var sourceDocument
              = new DOMParser().parseFromString(source, "application/xml");
    
            // Step 3: Perform the XSL transformation
            var xslt = new XSLTProcessor();
            xslt.importStylesheet(stylesheetDocument);
            var newFragment = xslt.transformToFragment(sourceDocument, document);
    
            // Step 4: Show the result
            document.body.appendChild(newFragment.firstChild);
          }
          // -->
        </script>
      </head>
      <body>
        <input type="submit" onclick="test()">
        Output:
      </body>
    </html>
    

    and a file test.xml

    <application xmlns="http://ns.adobe.com/air/application/1.0">
      <id>test</id>
      <filename>test</filename>
      <initialWindow>
        <content>test.html</content>
        <visible>true</visible>
      </initialWindow>
    </application>
    

    You can try it using the debugging runtime, for example:

    adl test.xml
    

    Klick the button, and it will say:

    example
    (source: lichteblau.com)