#!/usr/bin/env python
# This is a demonstration python script on how to parse a
# sablecc xml parser file using python and xpath.
# This script generates input for the graphviz's dot tool
#
# This script uses the PyXML module.

import xml.dom.minidom, xml.xpath

class XPathElem:
  def __init__(self, node): 
    self.node = node
  def value(self, path): return xml.xpath.Evaluate('string(' + path + ')', self.node)
  def nodes(self, path): return [ XPathElem(x) for x in xml.xpath.Evaluate(path, self.node) ]
  def test(self, path): return xml.xpath.Evaluate('boolean(' + path + ')', self.node)

root = XPathElem(xml.dom.minidom.parse('parser.xml'))

print 'digraph mygraph {'

for prod in root.nodes('/parser/productions/production'):
  print prod.value('@ename') + ' [shape=diamond,label="' + prod.value('@name') + '"]'

  for alt in prod.nodes('alt'):
    print alt.value('@ename') + ' [shape=box,label="' + alt.value('../@name') + '.' + alt.value('@name') + '"]'
    print alt.value('../@ename') + ' -> ' + alt.value('@ename')

    for elem in alt.nodes('elem'):
      print elem.value('../@ename') + ' -> ' + elem.value('@etype') + ' [label="' + elem.value('@name') + elem.value('@modifier') + '"]'
      if elem.test('@is_token'):
        print elem.value('@etype') + '[shape=ellipse,label="' + elem.value('@type') + '"]'
    
print '}'




syntax highlighted by Code2HTML, v. 0.9.1