Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mxGraph: Create graph with XML

I am trying to create graph from xml file.

My JavaScript Code is-

function loadXML() {
console.log("Inside loadXML");
var doc = mxUtils.parseXml('<root><mxCell id="0"/><mxCell id="1" parent="0"/><mxCell id="2" value="&lt;img src=&quot;printer.png&quot; onClick=&quot;printer()&quot; style=&quot;width:40px;height:40px;&quot;&gt;&lt;img&gt;" style="shape=image" vertex="1" parent="1"><mxGeometry x="434" y="81" width="40" height="40" as="geometry"/></mxCell></root>');

console.log("XML Parse: " + doc);

var codec = new mxCodec(doc);

console.log("Node Length: " + doc.documentElement.childNodes.length);

var cells = new Array();
for (var i = 0; i < doc.documentElement.childNodes.length; i++) {
    console.log("Node ID: " + i);
    cells[i] = codec.decodeCell(doc.documentElement.childNodes[i]);
}

// import cells into the graph
var delta = mxClipboard.insertCount * mxClipboard.STEPSIZE;
var parent = graph.getDefaultParent();

graph.model.beginUpdate();
console.log("Cells Lenght: " + cells.length);
try
{
  for (var i = 0; i < cells.length; i++)
  {
    cells[i] = graph.importCells([cells[i]], delta, delta, parent)[0];
  }
}
finally
{
  graph.model.endUpdate();
}

// Increments the counter and selects the inserted cells
mxClipboard.insertCount++;
graph.setSelectionCells(cells);

}

In my XML I have configured only one node. But when I am loading my XML into graph, It's taking as two nodes, means for every node it's iterating as two times. Please someone help me what wrong I am doing.

like image 610
deen Avatar asked Dec 24 '22 01:12

deen


2 Answers

try this

 var xml = '<root><mxCell id="2" value="World!Vishal" vertex="1"><mxGeometry x="200" y="150" width="80" height="30" as="geometry"/></mxCell><mxCell id="3" edge="1" source="2"><mxGeometry relative="1" as="geometry"><mxPoint x="440" y="90" as="targetPoint"/></mxGeometry></mxCell></root>';
                     var doc = mxUtils.parseXml(xml);
                    var codec = new mxCodec(doc);
                    var elt = doc.documentElement.firstChild;
                    var cells = [];
                    while (elt != null){                
                      cells.push(codec.decodeCell(elt));
                        graph.refresh();
                      elt = elt.nextSibling;
                    }

                this.graph.addCells(cells);

Let me know if you have any issue.

like image 60
Vishal Kamal Avatar answered Jan 05 '23 12:01

Vishal Kamal


if you are using Grapheditor you can use its method (setGraphXml):

let doc = mxUtils.parseXml(xml);

myEditor.editor.setGraphXml(doc.documentElement);

where doc is the parsed XML and myEditor is your editor instance. you can get editor instance with :

const myEditor = new EditorUi(new Editor(urlParams['chrome'] == '1', themes));
like image 31
Ahmed El Damasy Avatar answered Jan 05 '23 11:01

Ahmed El Damasy