开发者

js parsing XML from JSP, storing values

I'm parsing XML and would like to store the values in an easy-to-read fashion.

I am getting mapShapes and mapPoints (so x and y coordinates). An (x,y) pair makes a point, a collection of points makes a Shape.

Here is some example XML that I would like to parse:

<?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>

I would like to end up with an array like

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

(this example XML only has one shape present, but there could be several.)

Thanks in advance for the help with an easy question =)

Here's some skeleton code:

shapeXmlHandler : function(xml){

    $(xml).find("mapShape").each(functio开发者_StackOverflown(){
        $(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());
        });
    });
}


Try using 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);
}

This should log something like

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

This can be done a bit slicker using .map() instead of .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);
}

And if there's any chance of working with JSON instead of XML, you don't need any custom parsing code at all! Just use $.parseJSON.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜