2
\$\begingroup\$

I am writing a small application that would interactively allow user for xml file manipulation with d3 interactive charts.

My xml file has the following hierarchy :

<?xml version="1.0" encoding="UTF-8" ?>
<testcase>

  <measurement>
    <type>M8015</type>
    <interval>15</interval>
  </measurement>
  <measurement>
    <type>M8016</type>
    <interval>15</interval>
  </measurement>
  <measurement>
    <type>M8020</type>
    <interval>15</interval>
  </measurement>
   ...
</testcase>

What would be the most effective way to get the data out of xml into 2 arrays (one for x axis type, and one for y axis interval).

I have tried the following but don't know if that's a good approach.

$(function() {
  var $mydata = new Array(1);
  $.get("./testcase.xml", function(xml) {

      var $chart = d3.select("body").append("div")
          .attr("class", "chart")
          .attr("id", "chart");

      $(xml).find('measurement').each(function(){
        var $meas = $(this);  
        var $type = $meas.find('type').text();
        var $interval = $meas.find('interval').text();

        $mydata.push({'type': $type, 'interval': $interval});
    });
});

Any suggestions if that's the correct way of handling this problem ?

\$\endgroup\$
1
\$\begingroup\$

I suggest you use JSON when manipulating the data because it's easier and less code compared to the same XML counterpart code - and much easier.

I can think of two ways you can do this:

  • Convert your files to JSON, if you can.

  • If you can't convert to JSON files, stay with what you are doing, and read the XML but convert them to JS objects before handing them over to the chart. There are XML-to-JSON libraries out there which you can use.

A similar data structure in JSON would look like

{
  "testcase" : {
    "measurement" : [
      {
        "type" : "M8015",
        "interval" : 15
      },{
        "type" : "M8016",
        "interval" : 15
      },{
        "type" : "M8020",
        "interval" : 15
      }
    ]
  }
}

And it's a matter of plucking out the data:

var myData = data.testcase.measurement;
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.