js从JSP解析XML,存储值

问题描述:

我正在解析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

尝试使用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