Skip to content

Instantly share code, notes, and snippets.

@benjaminaaron
Created June 30, 2020 17:40
Show Gist options
  • Save benjaminaaron/7ba96858ae215b8103b6dcab777ff464 to your computer and use it in GitHub Desktop.
Save benjaminaaron/7ba96858ae215b8103b6dcab777ff464 to your computer and use it in GitHub Desktop.
A node.js script to add node ids as node labels for a GraphML format readable by yEd. As next step after exporting without the label apparatus.
const fs = require('fs');
const parser = require('xml2json');
const format = require('xml-formatter');
// true only for debugging, it messes the labels up because the space after <y:NodeLabel> and before the string gets included
const prettyPrint = false;
const replaceAll = (str, find, replace) => {
return str.replace(new RegExp(find, 'g'), replace);
};
const cleanId = id => {
id = replaceAll(id, '<', '&lt;');
id = replaceAll(id, '>', '&gt;');
id = replaceAll(id, '&', '&amp;');
return id;
};
fs.readFile( './dev.xml', (err, data) => {
let jsonIn = JSON.parse(parser.toJson(data, { reversible: true }));
let nodes = jsonIn.graph.node;
let edges = jsonIn.graph.edge;
// doesn't work if its just one node or one edge, then they are not an array but one object
for (let i = 0; i < nodes.length; i ++) {
let id = cleanId(nodes[i].id);
nodes[i] = {
id: id,
data: {
key: 'd6',
'y:ShapeNode' : {
'y:NodeLabel': {
'$t': id
}
}
}
};
}
for (let j = 0; j < edges.length; j ++) {
edges[j] = {
source: cleanId(edges[j].source),
target: cleanId(edges[j].target)
}
}
let jsonOut = {
graphml: {
'xmlns': 'http://graphml.graphdrawing.org/xmlns',
'xmlns:java': 'http://www.yworks.com/xml/yfiles-common/1.0/java',
'xmlns:sys': 'http://www.yworks.com/xml/yfiles-common/markup/primitives/2.0',
'xmlns:x': 'http://www.yworks.com/xml/yfiles-common/markup/2.0',
'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'xmlns:y': 'http://www.yworks.com/xml/graphml',
'xmlns:yed': 'http://www.yworks.com/xml/yed/3',
'xsi:schemaLocation': 'http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd',
// key: {
// for: 'hah',
// id: 'd6',
// 'yfiles.type': 'nodegraphics'
// },
// DOES NOT WORK, it gets mixed up with the first node somehow
// copy this above <graph> manually: <key for="node" id="d6" yfiles.type="nodegraphics"/>
graph: {
id: jsonIn.graph.id,
node: nodes,
edge: edges
}
}
};
let xml = parser.toXml(JSON.stringify(jsonOut));
if (prettyPrint) {
xml = format(xml);
}
fs.writeFile('out.graphml', xml, (err, data) => {
if (err) { console.log(err); }
else { console.log('export done'); }
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment