Schema ns = graph.getNodeTable().getSchema();
Schema es = graph.getEdgeTable().getSchema();
checkGraphMLSchema(ns);
checkGraphMLSchema(es);
XMLWriter xml = new XMLWriter(new PrintWriter(os));
xml.begin(Tokens.GRAPHML_HEADER, 2);
xml.comment("prefuse GraphML Writer | "
+ new Date(System.currentTimeMillis()));
// print the graph schema
printSchema(xml, Tokens.NODE, ns, null);
printSchema(xml, Tokens.EDGE, es, new String[] {
graph.getEdgeSourceField(), graph.getEdgeTargetField()
});
xml.println();
// print graph contents
xml.start(Tokens.GRAPH, Tokens.EDGEDEF,
graph.isDirected() ? Tokens.DIRECTED : Tokens.UNDIRECTED);
// print the nodes
xml.comment("nodes");
Iterator nodes = graph.nodes();
while ( nodes.hasNext() ) {
Node n = (Node)nodes.next();
if ( ns.getColumnCount() > 0 ) {
xml.start(Tokens.NODE, Tokens.ID, String.valueOf(n.getRow()));
for ( int i=0; i<ns.getColumnCount(); ++i ) {
String field = ns.getColumnName(i);
xml.contentTag(Tokens.DATA, Tokens.KEY, field,
n.getString(field));
}
xml.end();
} else {
xml.tag(Tokens.NODE, Tokens.ID, String.valueOf(n.getRow()));
}
}
// add a blank line
xml.println();
// print the edges
String[] attr = new String[]{Tokens.ID, Tokens.SOURCE, Tokens.TARGET};
String[] vals = new String[3];
xml.comment("edges");
Iterator edges = graph.edges();
while ( edges.hasNext() ) {
Edge e = (Edge)edges.next();
vals[0] = String.valueOf(e.getRow());
vals[1] = String.valueOf(e.getSourceNode().getRow());
vals[2] = String.valueOf(e.getTargetNode().getRow());
if ( es.getColumnCount() > 2 ) {
xml.start(Tokens.EDGE, attr, vals, 3);
for ( int i=0; i<es.getColumnCount(); ++i ) {
String field = es.getColumnName(i);
if ( field.equals(graph.getEdgeSourceField()) ||
field.equals(graph.getEdgeTargetField()) )
continue;
xml.contentTag(Tokens.DATA, Tokens.KEY, field,
e.getString(field));
}
xml.end();
} else {
xml.tag(Tokens.EDGE, attr, vals, 3);
}
}
xml.end();
// finish writing file
xml.finish("</"+Tokens.GRAPHML+">\n");
}