Parsing Graph Data

Once you're familiar with using the graph data structure you can load a file using a URLLoader and use its contents to populate an IGraph. One example might be create nodes and edges from XML. Here's a quick look at some code that might be used.

function loaderCompleteHandler(evt:Event):void
{
  var loader:URLLoader = evt.target as URLLoader;
  var rawData:String = loader.data;
  var xmlData:XML = XML(loader.data);
 
  var graph:IGraph = new LinkedGraph();
  for each (var nodeElem:XML in xmlData.node)
  {
    graph.addNode(
      nodeElem.@id,
      {label: nodeElem.@label});
  }
}

In the above code we define the event handler for the URLLoader's Event.COMPLETE event. The handler grabs the raw data that was just loaded and parses it as XML. Then, it examines each of the <node> elements and adds a new node to the graph, using the "id" and "label" attributes as node data values.

Using an IGraphParser

Sometimes it's useful to factor out the parsing functionality to a class. One reason you might do this is because you're parsing a common graph data format. The DefaultGraphParser, for example, is setup to parse XML files that look like this:

<?xml version="1.0" encoding="UTF-8"?>
<graph_data>
  <nodes>
    <node id="n0" label="Jerry" />
    <node id="n1" label="Louise" />
  </nodes>
  <edges>
    <edge id="e0"
      tail_node_id="n0"
      head_node_id="n1" />
  </edges>
</graph_data>

So how do we actually put the graph parser to use in our code? If you're loading data directly from a file using a URLLoader or Flex's webservice API then there isn't much to change.

Updating the example above to use the DefaultGraphParser, your event handler would now look like this:

function loaderCompleteHandler(evt:Event):void
{
  var loader:URLLoader = evt.target as URLLoader;
  var rawData:String = loader.data;
 
  var graph:IGraph = new LinkedGraph();
  var parser:IGraphParser = new DefaultGraphParser();
  parser.parse(graph, rawData);
}

That's it. Now the nodes and edges present in the XML file have been added to the graph.

Now that your data has been loaded, you can display it using a Constellation component directly, or you can manipulate it and display a subset instead. This subset is typically called the "view" because it's the portion of the data that is actually visible.

constellation.dataProvider = graph;
var aNode:LinkedNode =
    graph.getNodeByID('n0') as LinkedNode;
var view:IGraph = aNode.getTree(2);
constellation.dataProvider = view;