次の XML ファイル スニペットがあるとします。
<properties>
<one>ONE</one>
<two>TWO</two>
<three>THREE</three>
</properties>
次の 2 つの配列が必要です。
(ONE, TWO, THREE)
(one, two, three)
またはハッシュも適切です。XML:Smart
すでにたくさん使っているので、できれば使いたいです。
御時間ありがとうございます。
次の XML ファイル スニペットがあるとします。
<properties>
<one>ONE</one>
<two>TWO</two>
<three>THREE</three>
</properties>
次の 2 つの配列が必要です。
(ONE, TWO, THREE)
(one, two, three)
またはハッシュも適切です。XML:Smart
すでにたくさん使っているので、できれば使いたいです。
御時間ありがとうございます。
XML::Smart を紹介してくれてありがとう。それは私を通り過ぎましたが、ユビキタスな XML::Simple よりもはるかに優れているようです。
XML にハッシュとしてアクセスする必要があるようです。これは XML::Simple に似ていますが、この場合、ハッシュは実際のハッシュではなく結合されたハッシュであるため、実装がより堅牢になります。
メソッドを使用して要素nodes
内のノードのリストにアクセスし、<properties>
各要素のタグ名とテキスト コンテンツを と でフェッチしkey
ますcontent
。
ここにいくつかのコードがあります。
use strict;
use warnings;
use XML::Smart;
my $xml = <<'XML';
<properties>
<one>ONE</one>
<two>TWO</two>
<three>THREE</three>
</properties>
XML
my $smart = XML::Smart->new($xml);
my @nodes = $smart->{properties}->nodes;
my @text = map $_->content, @nodes;
my @names = map $_->key, @nodes;
printf "(%s)\n", join ', ', @text;
printf "(%s)\n", join ', ', @names;
出力
(ONE, TWO, THREE)
(one, two, three)
を使用XML::Simple
して XML を解析できます。次に、キーと値のペアを配列に抽出するだけです。
use strict;
use warnings;
use Data::Dumper;
use XML::Simple;
my $file = shift;
my $xml = XMLin($file); # $xml is now a hash ref with the data
my @keys = keys %$xml; # extract hash keys
my @vals = values %$xml; # extract hash values
print Dumper \@keys, \@vals;
XML::Smart で早速試してみました。このコードは機能します。
use strict;
use feature qw(say);
use XML::Smart;
my %config;
my $str = qq~<properties>
<one>ONE</one>
<two>TWO</two>
<three>THREE</three>
</properties>~;
my $XML = XML::Smart->new($str);
my @nodes = $XML->{properties}->nodes();
foreach my $k (@nodes) {
say "$k: ", $k->key;
$config{$k} = $k->key;
}
print Dumper \%config;
次のように出力されます。
ONE: one
TWO: two
THREE: three
$VAR1 = {
'TWO' => 'two',
'THREE' => 'three',
'ONE' => 'one'
};
それはすべてドキュメントにあります:key-method、nodes-method
それを2つの配列に入れるのは難しいようです。多分i()-methodを見てください。