javascriptmxgraph

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.


Solution

  • 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.