読み込み
Example: part1.xml
<config>
<user>Freddy</user>
<passwd>hogehoge</passwd>
<books>
<book author="Ernest Miller Hemingway" title="The Old Man and the Sea"/>
<book author="Mark Twain" title="The Adventures of Tom Sawyer"/>
</books>
</config>
Example: part1.pl
use strict;
use utf8;
use XML::Simple;
use Data::Dumper;
print Dumper (XML::Simple->new()->XMLin());
my $config = XML::Simple->new()->XMLin();
print "user:" . $config->{user} . "\n";
print "password: " . $config->{passwd} . "\n";
print "book[0].author: " . $config->{books}->{book}[0]->{author} . "\n";
print "book[0].title: " . $config->{books}->{book}[0]->{title} . "\n";
XML ファイル, Perl スクリプトのファイル名を part1 としておくことで自動的にスクリプトから part1.xml を読み込んでくれる。
>perl part1.pl
could not find ParserDetails.ini in C:/usr/Perl/site/lib/XML/SAX
$VAR1 = {
'passwd' => 'hogehoge',
'user' => 'Freddy',
'books' => {
'book' => [
{
'title' => 'The Old Man and the Sea',
'author' => 'Ernest Miller Hemingway'
},
{
'title' => 'The Adventures of Tom Sawyer',
'author' => 'Mark Twain'
}
]
}
};
user:Freddy
password: hogehoge
book[0].author: Ernest Miller Hemingway
book[0].title: The Old Man and the Sea
書き込みExample: part2.pl
use strict;
use utf8;
use XML::Simple;
use Data::Dumper;
print Dumper (XML::Simple->new()->XMLin("part1.xml"));
my $simple = XML::Simple->new();
my $config = $simple->XMLin("part1.xml");
print "user:" . $config->{user} . "\n";
print "password: " . $config->{passwd} . "\n";
print "book[0].author: " . $config->{books}->{book}[0]->{author} . "\n";
print "book[0].title: " . $config->{books}->{book}[0]->{title} . "\n";
$config->{passwd} = "new_password";
$simple->XMLout($config,
OutputFile => 'output.xml',
XMLDecl => "");
このスクリプトを実行すると以下の output.xml が生成されるExample: output.xml
<?xml version='1.0'?>
<opt passwd="new_password" user="Freddy">
<books>
<book author="Ernest Miller Hemingway" title="The Old Man and the Sea" />
<book author="Mark Twain" title="The Adventures of Tom Sawyer" />
</books>
</opt>
0 件のコメント:
コメントを投稿