XML形式ファイルを読み込んで配列にする「JKL.ParseXML」JavaScriptプラグインは便利なのでよく使っている。
しかし、既に読み込まれたXML形式の文字列を扱うには「JKL.ParseXML」は使えない。
そこで$.parseXMLを使ってみた。この$.parseXMLはXML形式の文字列をオブジェクト化するものである。
XML形式の文字列が得られたとき、それを解析してオブジェクト化しておくとJavaScriptプログラミングで処理がしやすくなる。
XMLファイル
<?xml version="1.0" encoding="Shift_JIS"?>
<root>
<customer>
<title>昆虫1</title>
<thmb>http://sample.com/thmb/bug_01.jpg</thmb>
<file>http://sample.com/images/bug_01.jpg</file>
</customer>
<customer>
<title>昆虫2</title>
<thmb>http://sample.com/thmb/bug_02.jpg</thmb>
<file>http://sample.com/images/bug_02.jpg</file>
</customer>
<customer>
<title>昆虫3</title>
<thmb>http://sample.com/thmb/bug_03.jpg</thmb>
<file>http://sample.com/images/bug_03.jpg</file>
</customer>
<customer>
<title>昆虫4</title>
<thmb>http://sample.com/thmb/bug_04.jpg</thmb>
<file>http://sample.com/images/bug_04.jpg</file>
</customer>
<customer>
<title>昆虫5</title>
<thmb>http://sample.com/thmb/bug_05.jpg</thmb>
<file>http://sample.com/images/bug_05.jpg</file>
</customer>
</root>
XMLファイルを読込んで処理するJavaScript
$.get('picdef.xml').done(function(data,statusText,jqXHR){
// 読み込んだXMLから配列を作る
var doc = $.parseXML(data);
var customers = doc.getElementsByTagName('customer');
for(var i = 0;i<customers.length; i++){
var customer = customers.item(i);
var node = customer.getElementsByTagName('thmb').item(0);
var thmb_name = node.firstChild.nodeValue;
var node = customer.getElementsByTagName('file').item(0);
var file_name = node.firstChild.nodeValue;
bugs[i] = { thmb:thmb_name, name:file_name };
}
});