How to parse KML files using perl?

ぃ、小莉子 提交于 2019-12-04 09:15:34

How about:

while (my ($key, $folder) = each %{$myFile->{Document}{Folder}{Placemark}})  {
    print $folder->{Point}->{coordinates}."\n";
}

output:

80.2437973022461,13.106230102044576,0.0
80.24688720703125,13.096198508196448,0.0
80.23435592651367,13.094024942328286,0.0

In your code, you're using

foreach my $folder (@{$myFile->{Document}->{Folder}->{Placemark}})  {
    print $folder->{Point}->{coordinates}."\n";
}

assuming $myFile->{Document}->{Folder}->{Placemark} is a reference to an array. But it isn't, it is a reference to a hash, so you have to walk thru it and foreach pair of (key,value) extract the coordinate from the value.

I don't think I would use XML::Simple for this.

With XML::Twig this is what you would write:

#!/usr/bin/perl

use strict;
use warnings;

use 5.10.0; # to get 'say'

use XML::Twig;

XML::Twig->new( twig_roots => { coordinates => sub { say $_->text; } })
         ->parsefile( $ARGV[0]);

Another possibility is to use XML::LibXML and XPaths. The advantage of XPaths is that these are also available to other languages, so other developer may understand your code. The disadvantage of XPaths is that their usage is not anymore nice in presence of namespaces (which is the case here), leading to some ugly-looking workarounds like using the local-name() function.

Here's a sample script:

use XML::LibXML;
my $doc = XML::LibXML->new->parse_file('ExperimentMap.kml');
for my $coordinate_node ($doc->findnodes('//*[local-name()="coordinates"]')) {
    print $coordinate_node->textContent, "\n";
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!