#!/usr/bin/perl
# This is a demonstration perl script on how to parse a
# sablecc xml parser file using xpath.
# This script generates input for the graphviz's dot tool
#
# You have to install XML::LibXML and XML::LibXML::XPathContext.

use XML::LibXML;
use XML::LibXML::XPathContext;

my $parser = new XML::LibXML;
my $xml = $parser->parse_file("parser.xml");
my $xpath = XML::LibXML::XPathContext->new($xml);

print "digraph mygraph {\n";

foreach my $prod ($xpath->findnodes('/parser/productions/production')) {
  print $prod->findvalue('@ename').' [shape=diamond,label="'.$prod->findvalue('@name')."\"]\n";

  foreach my $alt ($prod->findnodes('alt')) {
    print $alt->findvalue('@ename') . ' [shape=box,label="' . $alt->findvalue('../@name') . '.' . $alt->findvalue('@name') . "\"]\n";
    print $alt->findvalue('../@ename') . ' -> ' . $alt->findvalue('@ename') . "\n";

    foreach my $elem ($alt->findnodes('elem')) {
      print $elem->findvalue('../@ename') . ' -> ' . $elem->findvalue('@etype') . ' [label="' . $elem->findvalue('@name') . $elem->findvalue('@modifier') . "\"]\n";
      if ( $elem->findvalue('@is_token') ) {
        print $elem->findvalue('@etype') . '[shape=ellipse,label="' . $elem->findvalue('@type') . "\"]\n";
      }
    }
  }
}

print "}\n";



syntax highlighted by Code2HTML, v. 0.9.1