DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = null;
try {
docBuilder = dbfac.newDocumentBuilder();
} catch (ParserConfigurationException pce) {
throw new IOError(new IOException(pce));
}
Document doc = docBuilder.newDocument();
Element root = doc.createElement("gexf");
root.setAttribute("xmlns","http://www.gexf.net/1.2draft");
root.setAttribute("xmlns:viz", "http://www.gexf.net/1.2draft/viz");
root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
root.setAttribute("version","1.2");
root.setAttribute("xsi:schemaLocation","http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd");
doc.appendChild(root);
Element graph = doc.createElement("graph");
graph.setAttribute("defaultedgetype","undirected");
root.appendChild(graph);
Element nodes = doc.createElement("nodes");
graph.appendChild(nodes);
Element edges = doc.createElement("edges");
graph.appendChild(edges);
IntIterator vIter = g.vertices().iterator();
while (vIter.hasNext()) {
int vertex = vIter.next();
Element node = doc.createElement("node");
node.setAttribute("id", String.valueOf(vertex));
if (useLabels)
node.setAttribute("label", vertexLabels.lookup(vertex));
else
node.setAttribute("label", String.valueOf(vertex));
nodes.appendChild(node);
}
ColorGenerator cg = null;
if (useColors)
cg = new ColorGenerator();
int edgeId = 0;
for (E e : g.edges()) {
Element edge = doc.createElement("edge");
edges.appendChild(edge);
edge.setAttribute("id", "" + (edgeId++));
edge.setAttribute("source", String.valueOf(e.from()));
edge.setAttribute("target", String.valueOf(e.to()));
edge.setAttribute("label", String.valueOf(e.edgeType()));
if (useColors) {
Element cEdge = doc.createElement("viz:color");
edge.appendChild(cEdge);
Color c = edgeColors.get(e.edgeType());
if (c == null) {
c = cg.next();
edgeColors.put(e.edgeType(), c);
}
cEdge.setAttribute("r", String.valueOf(c.getRed()));
cEdge.setAttribute("g", String.valueOf(c.getGreen()));
cEdge.setAttribute("b", String.valueOf(c.getBlue()));
}
}
// Set up a transformer
try {
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "2");
// Create string from xml tree
BufferedOutputStream bos =
new BufferedOutputStream(new FileOutputStream(f));
StreamResult result = new StreamResult(bos);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
bos.close();
} catch (TransformerException te) {
throw new IOError(new IOException(te));
}
}