###前提・実現したいこと
下記のようなJavaScriptとxmlファイルがあるとします。
変数shapeの値に一致する<shape>の中で、<category>の<id>を見ていき、変数category_idの値と一致した場合、<item>の<sample_src>をHTMLのimgタグとして出力する。
ということを行いたいのですが、どう記述するとスマートに目的のものを取得できるでしょうか?
ご回答を頂けると助かります_(..)
###該当のソースコード
javascript
1var shape = "aaa01"; 2var category_id = "ccc02";
xml
1<?xml version="1.0" encoding="UTF-8"?> 2<info> 3 <shape type="aaa01"> 4 <item type="bbb01"> 5 <id>bbb01</id> 6 <category> 7 <id>ccc01</id> 8 </category> 9 <sample_src>assets/test1.png</sample_src> 10 </item> 11 <item type="bbb02"> 12 <id>bbb02</id> 13 <category> 14 <id>ccc01</id> 15 <id>ccc02</id> 16 </category> 17 <sample_src>assets/test2.png</sample_src> 18 </item> 19 </shape> 20 <shape type="aaa02"> 21 <item type="bbb01"> 22 <id>bbb01</id> 23 <category> 24 <id>ccc01</id> 25 <id>ccc02</id> 26 </category> 27 <sample_src>assets/test1.png</sample_src> 28 </item> 29 <item type="bbb02"> 30 <id>bbb02</id> 31 <category> 32 <id>ccc01</id> 33 <id>ccc02</id> 34 </category> 35 <sample_src>assets/test2.png</sample_src> 36 </item> 37 </shape> 38</info> 39
###試したこと
下記のように記述すると一応目的のもの(この場合、<shape type="aaa01">内の<item type="bbb02">内の<sample_src>の要素)が取得されます。
しかし、この書き方はかなり回りくどいことをしているような気がして…
javascript
1$.ajax({ 2 url: "xml/test.xml", 3 type: "GET", 4 dataType: "xml", 5 timeout: 1000, 6 error: function(){ 7 alert("ロード失敗"); 8 }, 9 success: function(xml){ 10 $(xml).find("shape").each(function(){ 11 if($(this).attr("type") == shape){ 12 $(this).find("item").each(function(){ 13 $(this).children("category").children("id").each(function(){ 14 if ($(this).text() == color_category) { 15 $(this).parent("category").parent("item").each(function(){ 16 $("#tabBox1 ul").append('<li><img src="' + $(this).find('sample_src').text() + '"></li>'); 17 }); 18 } 19 }); 20 }); 21 } 22 }); 23 } 24});
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/06/15 06:40