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());
});
});
}
答
尝试使用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] .point [0] .x = first x point'等等) – 2011-06-08 18:59:10
好的呼叫。我不确定如何完成目标,但我非常接近。我真的不知道什么是最好的方法是将xml数据放入数组中,因此我一直在寻求建议 – sova 2011-06-08 19:02:49