使用d3.xml而不是d3.json绘制可折叠缩进树

时间:2015-01-28 04:47:19

标签: javascript d3.js tree hierarchy

我能够使用可折叠的缩进树来使用JSON示例文件正常工作;但是,我无法修改代码以使用XML文件。下面是我的示例JSON文件,示例XML文件,并尝试修改.js文件以使用XML而不是JSON。

我认为这些是我必须修改但不确定的代码的关键区域:

d3.xml("d3/simple-flare.xml", "application/xml", function (error, flare) {
        flare.x0 = 0;
        flare.y0 = 0;
        update(root = flare);
    });

...

function update(source) {

        // Compute the flattened node list. TODO use d3.layout.hierarchy.
        var nodes = tree.nodes(root);

...

// Update the links…
        var link = svg.selectAll("path.link")
            .data(tree.links(nodes), function (d) { return d.target.id; });

简单flare.json

{
 "name": "flare",
 "children": [
  {
   "name": "analytics",
   "children": [
    {
     "name": "cluster",
     "children": [
      {"name": "AgglomerativeCluster", "size": 3938},
      {"name": "CommunityStructure", "size": 3812},
      {"name": "MergeEdge", "size": 743}
     ]
    },
    {
     "name": "graph",
     "children": [
      {"name": "BetweennessCentrality", "size": 3534},
      {"name": "LinkDistance", "size": 5731}
     ]
    },
    {
     "name": "optimization",
     "children": [
      {"name": "AspectRatioBanker", "size": 7074}
     ]
    }
   ]
  },
  {
   "name": "animate",
   "children": [
    {"name": "Easing", "size": 17010},
    {"name": "FunctionSequence", "size": 5842},
    {
     "name": "interpolate",
     "children": [
      {"name": "ArrayInterpolator", "size": 1983},
      {"name": "ColorInterpolator", "size": 2047},
      {"name": "DateInterpolator", "size": 1375},
      {"name": "Interpolator", "size": 8746},
      {"name": "MatrixInterpolator", "size": 2202},
      {"name": "NumberInterpolator", "size": 1382},
      {"name": "ObjectInterpolator", "size": 1629},
      {"name": "PointInterpolator", "size": 1675},
      {"name": "RectangleInterpolator", "size": 2042}
     ]
    },
    {"name": "ISchedulable", "size": 1041},
    {"name": "Parallel", "size": 5176},
    {"name": "Pause", "size": 449},
    {"name": "Scheduler", "size": 5593},
    {"name": "Sequence", "size": 5534},
    {"name": "Transition", "size": 9201},
    {"name": "Transitioner", "size": 19975},
    {"name": "TransitionEvent", "size": 1116},
    {"name": "Tween", "size": 6006}
   ]
  }
 ]
}

简单flare.xml

<?xml version="1.0" encoding="UTF-8" ?>
<flare>
  <analytics>
     <cluster>
        <agglomerativeCluster>3938</agglomerativeCluster>
        <communityStructure>3812</communityStructure>
        <mergeEdge>743</mergeEdge>
     </cluster>
     <graph>
        <test>3343</test>
        <mmmm>3353</mmmm>
        <lalala>454</lalala>
     </graph>
     <optimization>
        <AspectRatio>7074</AspectRatio>
     </optimization>
  </analytics>
</flare>

collapseIndentTree.js

// Changes XML to JSON
function xmlToJson(xml) {

    // Create the return object
    var obj = {};

    if (xml.nodeType == 1) { // element
        // do attributes
        if (xml.attributes.length > 0) {
            obj["@attributes"] = {};
            for (var j = 0; j < xml.attributes.length; j++) {
                var attribute = xml.attributes.item(j);
                obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
            }
        }
    } else if (xml.nodeType == 3) { // text
        obj = xml.nodeValue;
    }

    // do children
    if (xml.hasChildNodes()) {
        for (var i = 0; i < xml.childNodes.length; i++) {
            var item = xml.childNodes.item(i);
            var nodeName = item.nodeName;
            if (typeof (obj[nodeName]) == "undefined") {
                obj[nodeName] = xmlToJson(item);
            } else {
                if (typeof (obj[nodeName].push) == "undefined") {
                    var old = obj[nodeName];
                    obj[nodeName] = [];
                    obj[nodeName].push(old);
                }
                obj[nodeName].push(xmlToJson(item));
            }
        }
    }
    return obj;
};

function indenttree() {
    var margin = { top: 30, right: 20, bottom: 30, left: 20 },
    width = 960 - margin.left - margin.right,
    barHeight = 20,
    barWidth = width * .8;

    var i = 0,
        duration = 400,
        root;

    var tree = d3.layout.tree()
        .nodeSize([0, 20]);

    var diagonal = d3.svg.diagonal()
        .projection(function (d) { return [d.y, d.x]; });

    var svg = d3.select(".nester_wrap").append("svg")
        .attr("width", width + margin.left + margin.right)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    d3.xml("d3/simple-flare.xml", "application/xml", function (error, flare) {
        var flareJSON = xmlToJson(flare)
        flareJSON.x0 = 0;
        flareJSON.y0 = 0;

        var xmlText = new XMLSerializer().serializeToString(flare);
        var xmlTextNode = document.createTextNode(xmlText);
        var parentDiv = document.getElementById('footerArea');
        parentDiv.appendChild(xmlTextNode);

        alert(JSON.stringify(flareJSON));

        update(root = flare);
        //update(root = flareJSON);
        //update(root = d3.select(flare).selectAll("*")[0]);
        //update(root = flare.selectNodes("//*")[0]);
    });

    /*
    d3.json("d3/simple-flare.json", function (error, flare) {
        flare.x0 = 0;
        flare.y0 = 0;
        update(root = flare);
    });

    //notes
    d3.json("flare.json", function(root) {
    var nodes = flatten(root),
        links = d3.layout.tree().links(nodes);

    d3.xml("flare.xml", "application/xml", function(xml) {
        var nodes = self.nodes = d3.select(xml).selectAll("*")[0],
            links = self.links = nodes.slice(1).map(function(d) {
                return {source: d, target: d.parentNode};
            });
    */

    function update(source) {

        // Compute the flattened node list. TODO use d3.layout.hierarchy.
        var nodes = tree.nodes(root);

        var height = Math.max(500, nodes.length * barHeight + margin.top + margin.bottom);

        d3.select("svg").transition()
            .duration(duration)
            .attr("height", height);

        d3.select(self.frameElement).transition()
            .duration(duration)
            .style("height", height + "px");

        // Compute the "layout".
        nodes.forEach(function (n, i) {
            n.x = i * barHeight;
        });

        // Update the nodes…
        var node = svg.selectAll("g.node")
            .data(nodes, function (d) { return d.id || (d.id = ++i); });

        var nodeEnter = node.enter().append("g")
            .attr("class", "node")
            .attr("transform", function (d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
            .style("opacity", 1e-6);

        // Enter any new nodes at the parent's previous position.
        nodeEnter.append("rect")
            .attr("class", "indent")
            .attr("y", -barHeight / 2)
            .attr("height", barHeight)
            .attr("width", barWidth)
            .style("fill", color)
            .on("click", click);

        nodeEnter.append("text")
            .attr("class", "indent")
            .attr("dy", 3.5)
            .attr("dx", 5.5)
            .text(function (d) { return d.name; });

        // Transition nodes to their new position.
        nodeEnter.transition()
            .duration(duration)
            .attr("transform", function (d) { return "translate(" + d.y + "," + d.x + ")"; })
            .style("opacity", 1);

        node.transition()
            .duration(duration)
            .attr("transform", function (d) { return "translate(" + d.y + "," + d.x + ")"; })
            .style("opacity", 1)
          .select("rect")
            .style("fill", color);

        // Transition exiting nodes to the parent's new position.
        node.exit().transition()
            .duration(duration)
            .attr("transform", function (d) { return "translate(" + source.y + "," + source.x + ")"; })
            .style("opacity", 1e-6)
            .remove();

        // Update the links…
        var link = svg.selectAll("path.link")
            .data(tree.links(nodes), function (d) { return d.target.id; });

        // Enter any new links at the parent's previous position.
        link.enter().insert("path", "g")
            .attr("class", "link")
            .attr("d", function (d) {
                var o = { x: source.x0, y: source.y0 };
                return diagonal({ source: o, target: o });
            })
          .transition()
            .duration(duration)
            .attr("d", diagonal);

        // Transition links to their new position.
        link.transition()
            .duration(duration)
            .attr("d", diagonal);

        // Transition exiting nodes to the parent's new position.
        link.exit().transition()
            .duration(duration)
            .attr("d", function (d) {
                var o = { x: source.x, y: source.y };
                return diagonal({ source: o, target: o });
            })
            .remove();

        // Stash the old positions for transition.
        nodes.forEach(function (d) {
            d.x0 = d.x;
            d.y0 = d.y;
        });
    }

    // Toggle children on click.
    function click(d) {
        if (d.children) {
            d._children = d.children;
            d.children = null;
        } else {
            d.children = d._children;
            d._children = null;
        }
        update(d);
    }

    function color(d) {
        return d._children ? "#3182bd" : d.children ? "#c6dbef" : "#fd8d3c";
    }
}
var chart = indenttree();

1 个答案:

答案 0 :(得分:1)

我正要做类似的事情,而且,自从D3新手以来,首先在网上搜索并偶然发现了这个帖子。我得到了它的工作,这是我的发现(很可能是可以优化的)。

根据您的原始代码,我首先能够非常轻松地显示节点的文本:

nodeEnter.append("text")
         .attr("class", "indent")
         .attr("dy", 3.5)
         .attr("dx", 5.5)
         .text(function (d) { return d.tagName + " = " +
                               d.firstChild.nodeValue; });
//       .text(function (d) { return d.name; });

然后,获取节点之间的链接有点复杂(我使用firebug及其JS调试器来查看正在发生的事情)。 一次,以下缺失:

var nodes = tree.nodes(root);
var links = d3.layout.tree().links(nodes);  // missing
然而,只是这样做会抛出一个异常“[] .map而不是一个函数”,结果有点让人感到难过,因为我真的很喜欢你最初的想法直接遍历XML结构,而不是先将它转换为JSON。 / p>

在JS调试器中,我发现tree.nodes()函数通过深度和父属性很好地扩充了XML节点层次结构(如https://github.com/mbostock/d3/wiki/Tree-Layout所述),但它不会创建一个额外的属性子节点(可能因为在代表XML的DOM中,已经有一个名为children的成员 - 但是它的类型为HTMLCollection(这里是相关的东西:Difference between HTMLCollection, NodeLists, and arrays of objects),不幸的是,这似乎是上述异常的原因:D3期望一个数组调用map()但找到一个HTMLcollection。)

因此,似乎没有其他方法,除了首先将XML转换为JSON之前,您最初对此进行了评论。 然而,这种方法需要进行一些其他更改:

首先,现在使用JSON数据:

// update(root = flare);
update(root = flareJSON);

然后,撤消上面的更改:

nodeEnter.append("text")
        .attr("class", "indent")
        .attr("dy", 3.5)
        .attr("dx", 5.5)
        .text(function (d) { return d.name; });

现在,flareJSON既不包含父项也不包含子项,因此tree.nodes()不会生成任何有用的内容。我完全改变了这个功能(我忽略了属性XML的东西):

// Changes XML to JSON
function xmlToJson(xml)
{
  // ignore text leaves
  if(xml.hasChildNodes())
  {
    // Produce a node with a name
    var obj = { name: (xml.tagName || "root") + (xml.firstChild.nodeValue ? (" = " + xml.firstChild.nodeValue) : "") };

    // iterate over children
    for (var i = 0; i < xml.childNodes.length; i++)
    {
      // if recursive call returned a node, append it to children
      var child = xmlToJson(xml.childNodes.item(i));
      if(child)
      {
        (obj.children || (obj.children = [])).push(child);
      }
    }

    return obj;
  }

  return undefined;
};

现在它可以正常工作,我猜它应该: - )

如果最初的想法(直接绘制XML)有效,那仍然会很好,但这可能需要更改D3(见上文)......

编辑:呵呵,刚才发现了这个: How to have forEach available on pseudo-arrays returned by querySelectorAll? 如果我将其插入到JS代码中,那么基于XML的纯方法也可以工作(好吧,差不多,JS控制台中会出现一些警告,但我会继续尝试......