2011-06-08 29 views
0

我正在解析XML並希望以易於閱讀的方式存儲值。js從JSP解析XML,存儲值

我得到mapShapes和mapPoints(所以x和y座標)。一個(x,y)對形成一個點,一個點的集合形成一個形狀。

下面是一些示例XML,我想解析:

<?xml version='1.0'?> 
<mapQuery id='10918014'> 
    <mapShape id='429436'> 
     <mapPoint id='4259799'> 
      <x>-81.61508</x> 
      <y>41.52184</y> 
     </mapPoint> 
     <mapPoint id='4259800'> 
      <x>-81.61537</x> 
      <y>41.52181</y> 
     </mapPoint> 
     <mapPoint id='4259801'> 
      <x>-81.61538</x> 
      <y>41.522198</y> 
     </mapPoint> 
     <mapPoint id='4259802'> 
      <x>-81.61516</x> 
      <y>41.52222</y> 
     </mapPoint> 
     <mapPoint id='4259803'> 
      <x>-81.61508</x> 
      <y>41.52184</y> 
     </mapPoint> 
    </mapShape> 
</mapQuery> 

我想結束與像

shapes[0].point[0].x[0] = first x point 
shapes[0].point[0].y[0] = first y point 

的陣列(該例子中的XML僅具有本一種形狀,但可能有幾個)。

在此先感謝您的幫助,並提出了一個簡單的問題=)

下面是一些骨架代碼:

shapeXmlHandler : function(xml){ 

    $(xml).find("mapShape").each(function(){ 
     $(this).find("mapPoint").each(function() { 
      console.log('mapPoint: '+$(this).attr('id')); 
      console.log('x :'+$(this).find("x").text()); 
      console.log('y :'+$(this).find("y").text()); 
     }); 
    }); 
} 
+0

你有什麼問題?看起來不錯(除了我認爲你實際上想'形狀[0] .point [0] .x = first x point'等等) – 2011-06-08 18:59:10

+0

好的呼叫。我不確定如何完成目標,但我非常接近。我真的不知道什麼是最好的方法是將xml數據放入數組中,因此我一直在尋求建議 – sova 2011-06-08 19:02:49

回答

1

嘗試使用Array.push()

shapeXmlHandler : function(xml) 
{ 
    var shapes = []; 

    $(xml).find('mapShape').each(function() 
    { 
     var shape = []; 

     $(this).find('mapPoint').each(function() 
     { 
      var $p = $(this), 
       point = 
       { 
        x: $p.find('x').text(), 
        y: $p.find('y').text() 
       }; 

      shape.push(point); 
     }); 

     shapes.push(shape); 
    }); 

    console.log(shapes); 
} 

這應該登錄類似

[ 
    [ 
     {x: -81.61508, y: 41.52184}, 
     {x: -81.61537, y: 41.52181}, 
     ... 
    ] 
] 

這是可以做到使用.map()代替.each()有點滑頭:

shapeXmlHandler : function(xml) 
{ 
    var shapes = $(xml).find('mapShape').map(function() 
    { 
     return $(this).find('mapPoint').map(function() 
     { 
      var $p = $(this); 
      return { 
       x: $p.find('x').text(), 
       y: $p.find('y').text() 
      }; 
     }).get(); 
    }).get(); 

    console.log(shapes); 
} 

如果有任何機會窩國王與JSON而不是XML,你根本不需要任何自定義解析代碼!只需使用$.parseJSON即可。

+0

非常感謝您的詳盡解答。如果可以的話,會給你兩個upvotes =) – sova 2011-06-09 21:34:22

+0

謝謝,不用擔心。你最終使用了哪種方法? – 2011-06-09 22:03:26

+0

.map()是否需要.get()?除非我將.get()關閉,否則我不會得到任何控制檯輸出,但它顯示了比數組更多的東西(比如各種jQuery方法)。我正在使用第一種方法 - 我仍然不確定是否需要長時間保持輸入,所以我可能會在處理輸入時通過它 – sova 2011-06-13 19:32:00