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



我能够让可折叠的缩进树与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; });

simple-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}
   ]
  }
 ]
}

简单耀斑.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>

折叠缩进树.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();

我正要做类似的事情,而且,由于是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。

在 JS 调试器中,我发现 tree.nodes() 函数通过深度和父属性很好地增强了 XML 节点层次结构(如 https://github.com/mbostock/d3/wiki/Tree-Layout 此处所述),但它不会创建额外的属性子级(可能是因为在表示 XML 的 DOM 中,已经有一个名为 children 的成员 - 但是它是 HTMLCollection 类型(这里有一些相关的东西: HTMLCollection,NodeLists和对象数组之间的区别),不幸的是,这似乎是上述异常的原因:D3期望数组调用map(),但找到HTML集合)。

因此,除了首先将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 中进行更改(见上文)......

编辑:呵呵,刚刚发现这个:如何在 querySelectorAll 返回的伪数组上提供 forEach?如果我将其插入 JS 代码中,那么纯基于 XML 的方法也可以工作(好吧,几乎,JS控制台中会出现一些警告,但我会继续努力......

最新更新