views:

95

answers:

1

I'm working with a DSL based on an XML schema that supports functional language features such as loops, variable state with context, and calls to external Java classes. I'd like to write a tool which takes the XML document and converts it to, at the very least, something that looks like Java, where the <set> tags get converted to variable assignments, loops get converted to for loops, and so on.

I've been looking into ANTLR as well as standard XML parsers, and I'm wondering whether there's a recommended way to go about this. Can such an XML document be converted to something that's convertable to Java, if not directly?

I'm willing to write the parsing through SAX that writes an intermediate language based on each tag, if that's the recommended way, but the part that's giving me pause is the fact that it's context-based in the same way a language like Scheme is, with child elements of any tag being fully evaluated before the parent.

+2  A: 

You can do it with XSLT. Then just use to generate the code snippets you need.

(remember to set the output format to plain text)


EDIT: Sample XSLT script

Input - a.xml:

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="b.xsl"?>
<set name='myVar'>
  <concat>
    <s>newText_</s>
    <ref>otherVar</ref>
  </concat>
</set>

Script - b.xsl:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
  <xsl:strip-space elements="*"/>
  <xsl:output method="text" />

  <xsl:template match="set">
    <xsl:value-of select="@name"/>=<xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="concat">
    <xsl:for-each select="*">
      <xsl:if test="position() > 1">+</xsl:if>
      <xsl:apply-templates select="."/>
    </xsl:for-each>
  </xsl:template>

  <xsl:template match="ref">
    <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="s">
    <xsl:text>"</xsl:text>
    <xsl:apply-templates/>
    <xsl:text>"</xsl:text>
  </xsl:template>
</xsl:stylesheet>

Note that a.xml contain an instruction that will let XSLT-capable browsers render it with the stylesheet b.xsl. Firefox is such a browser. Open a.xml in firefox and you will see

myVar="newText_"+otherVar

Note that XSLT is a quite capable programming language, so there is a lot you can do.

Thorbjørn Ravn Andersen
Sorry, I'm a little lost -- could you give an example of how I would write a transformation from something like the following? <set name='myVar'><concat><s>newText_</s><ref>otherVar</ref></set> --> myVar = "newText_" + otherVar;
Jon
+1 for recommending an existing, readily available technology rather than making the OP jump through hoops. Now to find an appropriate XSLT library to turn this into an application...
Jon Purdy
Sorry for the delay, it took a while before I could actually try this. It's working for me fairly well, but it'll still have to be an intermediate language as I still need to do reference checking with variable scope and such.
Jon