title: Transform parse tree into XML
body: <p>I have a compiled grammar and I want to use it to transform an input sequence into an XML. Please note that in my case I have a very large grammar with many rules and I would like to avoid overriding each grammar rule in my code.</p>
  
  <p>I will use an example to avoid confusion. Let us have a following <strong>grammar</strong></p>
  
  <pre><code>grammar expr;
  
  prog: stat+ ;
  
  stat: expr NEWLINE
   | ID '=' expr NEWLINE
   | NEWLINE
  ;
  
  expr:  expr ('*'|'/') expr
   | INT
   | ID
   | '(' expr ')'
  ;
  
  ID : [a-zA-Z]+ ; // match identifiers
  INT : [0-9]+ ; // match integers
  NEWLINE:'\r'? '\n' ; // return newlines to parser (is end-statement signal)
  WS : [ \t]+ -&gt; skip ; // toss out whitespace
  </code></pre>
  
  <p><strong>Input sequence</strong></p>
  
  <pre><code>A = 10
  B = A * A
  </code></pre>
  
  <p><strong>Expected output</strong></p>
  
  <pre><code>&lt;prog&gt; 
      &lt;stat&gt; 
          A = 
          &lt;expr&gt; 10
          &lt;/expr&gt; 
          \r\n
      &lt;/stat&gt;  
      &lt;stat&gt; 
          B = 
          &lt;expr&gt;
              &lt;expr&gt;A&lt;/expr&gt; 
              * 
              &lt;expr&gt; A&lt;/expr&gt;
          &lt;/expr&gt; 
          \r\n
      &lt;/stat&gt;
  &lt;/prog&gt;
  </code></pre>
  
  <p>which corresponds to a parse tree </p>
  
  <p><a href="https://i.stack.imgur.com/jXzzL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jXzzL.png" alt="enter image description here"></a></p>
  
  <p>Currently I use an approach where I create a <code>ParseTree</code> and using the <code>toStringTree</code> method I generate the following string</p>
  
  <pre><code>(prog (stat A = (expr 10) \r\n) (stat B = (expr (expr A) * (expr A)) \r\n))
  </code></pre>
  
  <p>which I subsequently transform into the XML shown above (I use simple generic code working for any grammar). I find this approach dummy. Is it possible to solve it without <code>toStringTree</code>? I would like to avoid the need to override each grammar rule in my Visitor. (I have hundreds of them).</p>
  
  <p><strong>EDIT</strong> </p>
  
  <p>I basically need some kind of generic ParseTree serialization into the XML format. The major goal is that I will not have to write special serialization method in Java for each rule.</p>