mxGraph:使用 XML 创建图形

dee*_*een 4 javascript mxgraph

我正在尝试从 xml 文件创建图形。

我的 JavaScript 代码是-

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);

}
Run Code Online (Sandbox Code Playgroud)

在我的 XML 中,我只配置了一个节点。但是当我将我的 XML 加载到图中时,它被视为两个节点,这意味着它对每个节点迭代两次。请有人帮助我我做错了什么。

Vis*_*mal 6

尝试这个

 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);
Run Code Online (Sandbox Code Playgroud)

如果您有任何问题,请告诉我。