Make a diagram using XML and Graphviz

This is an old article from 2010 however it's still relevant.

require 'rexml/document'
include REXML

require 'rubygems'  # allows for the loading of gems
require 'graphviz'  # this loads the ruby-graphviz gem

# initialize new Graphviz graph
g = GraphViz::new( "structs", "type" => "graph" )
g[:rankdir] = "LR"

def get_doc(filename)
  Document.new(File.open(filename,'r').read)
end

doc_options = get_doc('graphviz_options.xml')
doc_nodes = get_doc('graphviz_nodes.xml')
doc_edges = get_doc('graphviz_edges.xml')

# set global node options

xpath_node = "records/option[summary/type='node']/records/attribute"
doc_options.root.elements.each(xpath_node) do |attribute|
  g.node[attribute.text('name').to_sym] = attribute.text('value')
end

xpath_edge = "records/option[summary/type='edge']/records/attribute"
doc_options.root.elements.each(xpath_edge) do |attribute|
  g.edge[attribute.text('name').to_sym] = attribute.text('value')
end

# add the nodes

doc_nodes.root.elements.each('records/node') do |node|
  g.add_node(node.attribute('id').to_s).label = node.text('label') + '1'
end

# add the edges

doc_edges.root.elements.each('records/edge') do |edge|
  a = edge.elements.each('records/node'){}
  g.add_edge(a[0].attribute('id').to_s, a[1].attribute('id').to_s).label = edge.text('summary/label').to_s
end

# output the file

out_type = doc_edges.root.text('summary/output_type')
out_file = doc_edges.root.text('summary/output_file')
g.output( "output" => out_type, :file => out_file )


file: graphviz_options.xml

screenshot of the output screenshot of the output

Tags:
Source:
2311hrs.txt
Published:
08-04-2014 23:11