資料是台南市國中男女生的人數,只取前三間學校的資料。
001.xml的內容
<ArrayOfgetOdataJHController.Statistic_CitySexStdCountsJHDTO
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/ebookApi.Controllers">
<getOdataJHController.Statistic_CitySexStdCountsJHDTO>
<num>221</num>
<school>下營國中</school>
<sex>男</sex>
</getOdataJHController.Statistic_CitySexStdCountsJHDTO>
<getOdataJHController.Statistic_CitySexStdCountsJHDTO>
<num>218</num>
<school>下營國中</school>
<sex>女</sex>
</getOdataJHController.Statistic_CitySexStdCountsJHDTO>
<getOdataJHController.Statistic_CitySexStdCountsJHDTO>
<num>241</num>
<school>土城高中</school>
<sex>男</sex>
</getOdataJHController.Statistic_CitySexStdCountsJHDTO>
<getOdataJHController.Statistic_CitySexStdCountsJHDTO>
<num>197</num>
<school>土城高中</school>
<sex>女</sex>
</getOdataJHController.Statistic_CitySexStdCountsJHDTO>
<getOdataJHController.Statistic_CitySexStdCountsJHDTO>
<num>114</num>
<school>大內國中</school>
<sex>男</sex>
</getOdataJHController.Statistic_CitySexStdCountsJHDTO>
<getOdataJHController.Statistic_CitySexStdCountsJHDTO>
<num>89</num>
<school>大內國中</school>
<sex>女</sex>
</getOdataJHController.Statistic_CitySexStdCountsJHDTO>
</ArrayOfgetOdataJHController.Statistic_CitySexStdCountsJHDTO>
Test01.html的原始碼
<!DOCTYPE html>
<head>
<title>D3.js測試</title>
<meta charset="utf-8">
</head>
<html>
<head>
<meta charset="utf-8" />
<title>Test10_D3.js</title>
<!-- d3.js的引用要放在Header內 -->
<script src="d3/d3.min.js"></script>
</head>
<body>
<h1>D3.js程式測試</h1><br />
<div id="div1" width="500" ></div>
<!-- D3.js的Scropt語法要放在Body內 -->
<script>
d3.xml("001.xml","application/xml", function(xml) {
var a = new Array();
//加上[0]或[0][0]的判斷,可以用Chrome的開發者工具查看
a[0] = d3.select(xml).selectAll("school")[0] ;
a[1] = d3.select(xml).selectAll("num")[0];
a[2] = d3.select(xml).selectAll("sex")[0];
var obj_a = new Array();
//重新串成陣列資料,因為政府的opendata xml並不符d3.js對資料格式的要求,
//d3.js可以是陣列內元素是物件或陣列 [ object,object,... ]或 [ array,array,array ]
//可以加上console.log取出物件,並由Chrome的開發者工具得知型態或資料
//例如:console.log(obj_a,"obj_a的物件")
//例如:data1=[ {x:1,y:2},{x:10,y:20} ] => [ object,object,... ]
//例如:data1=[ [1,2],[10,20] ] => [ array,array,array ]
for ( i = 0 ; i < a[0].length ; i++ ) {
obj_a[i] = { "school":a[0][i].textContent , "num":a[1][i].textContent,
"sex": a[2][i].textContent } ;
}
d3.select("#div1").selectAll("p")
.data(obj_a)
.enter()
.append("p")
.text(function(d) {
return d.school + " " + d.sex + " " + d.num;
}) ;
});
</script>
</body>
</html>
以Chrome開發工具除錯或用console.log輸出資訊,可以方便我們除錯。
例如下列的語法:
d3.xml("001.xml","application/xml", function(xml) {
t1 = d3.select(xml).selectAll("school");
console.log(t1,"test1_object");
});
由下圖可知t1是一個陣列 [Array[6]] ,而且只有1個元素Array[6],
而Array[6]又是一個陣列,有6個元素,最後才是值。
所以如果要取t1的「shcool」的值,則應使用t1[0][0]
console.log(t1[0][0].textContent,"test1_textContent");
但是如果改為t1=d3.select(xml).selectAll("school")[0];
由下圖可知t1仍是一個陣列,陣列內有6個值。
所以要取t1的「shcool」的值,則應使用t1[0]
console.log(t1[0].textContent,"test1_textContent");