下面是一個使用XML::Twig溶液。我認爲它做到了你想要的。它使用的XML :: Twig最顯着的特性是使用id => name
選項將name屬性作爲ID使用,因此可以直接使用$t->elt_id
和insert_new_elt
方法找到元素,以在樹中創建新元素。其簽名是(<position: before, after, first_child or last_child>, <tag_name>, <{attributes}>, <content>
),
#!/usr/bin/perl
use strict;
use warnings;
use XML::Twig;
my $t= XML::Twig->new(id => 'name', # treat the name attribute as an ID
pretty_print => 'indented'
)
->parse(\*DATA);
add_city($t, japan => "Kobe");
add_city($t, japan => "Tokyo");
add_city($t, china => "Beijing");
add_city($t, china => "Shanghai");
add_city($t, japan => "Kobe");
add_city($t, south_korea => "Seoul");
$t->print;
sub add_city
{ my($t, $country_name, $city_name)= @_;
my $country= $t->elt_id($country_name);
if(! $country)
{ warn "creating country '$country_name'\n";
$country= $t->root->insert_new_elt(last_child => country
=> { name => $country_name }
);
}
if($country->first_child(qq{city[text()="$city_name"]}))
{ warn "city '$city_name' already found in '$country_name', skipping\n";
return;
}
warn "adding '$city_name' to '$country_name', skipping\n";
$country->insert_new_elt(last_child => 'city', $city_name);
}
__DATA__
<countries>
<country name="japan">
</country>
<country name="china">
</country>
</countries>
對不起,我很困惑。我知道如何編寫XML內容。我的問題是關於如何將城市添加爲國家/地區代碼的最後一個條目。我是否需要遍歷所有現有的城市條目,並在達到最後一個標記時,需要在那裏添加新請求的城市。如何實現這一目標? – hari 2010-11-28 21:44:36
呃,如果你用解析器讀取XML文件,你將得到一個國家的哈希值,按鍵(最好的情況下)排序,每個國家包含每個國家的城市數組。因此,您只需從國家/地區哈希中選擇正確的值,獲取其城市數組並將其推入該數組。困難在哪裏? – Mithaldu 2010-11-28 21:55:49
感謝Mithaldu,我仍然在學習如何在Perl中使用XML。 – hari 2010-11-29 00:51:06