2010-11-29 8 views
1

このスレッドは、Perl script to populate an XML fileの続きです。Perlスクリプトを使用してXMLファイルの内容を変更する

私は変更したいファイルがある:私はこのリストには、ここで新しい国を追加したい

<?xml version="1.0" encoding="UTF-8"?> 
    <configuration start="earth"> 
    <country-list> 
     <country name="japan"> 
     <description></description> 
     <start>1900</start> 
     <end/> 
     </country> 
     <country name="italy"> 
     <description></description> 
     <start>1950</start> 
     <end/> 
     </country> 
     <country name="korea"> 
     <description></description> 
     <start>1800</start> 
     <end/> 
     </country> 
    </country-list> 
    </configuration> 

前の質問では、Perl script to populate an XML fileです。

#Get the list of cities as a list, then push "Tokyo" to it. 
push @{$doc->{countries}->{country}->{'japan-'}->{city}}, 'Tokyo'; 

これは新しいタグを追加するように提案されましたが、私の場合は「プッシュ」をどのくらい正確に使用できるかわかりません。正しいタグにマップできません。

+0

あなたの問題は? – cjm

+0

push @ {$ doc - > {configuration} - > {'country-list'} - > {country}}、$ platform_name; - 提案されたが、私は確信していない、どのように正確に私は新しい国を追加するためにプッシュを使用する必要があります。 – hari

答えて

1

私はXML::DOMがもっと簡単に使用できることを発見しました。それは少し冗長かもしれませんが、あなたはそれが何をしているのかを簡単に理解することができます。

use XML::DOM; 

#parse the file 
my $parser = new XML::DOM::Parser; 
my $doc = $parser->parsefile ("test.xml"); 
my $root = $doc->getDocumentElement(); 

#get the country-list element 
my $countryListElement = pop(@{$root->getElementsByTagName('country-list')}); 

#create a new country element 
my $newCountryElement= $doc->createElement('country'); 
$newCountryElement->setAttribute("name","England"); 

my $descElement= $doc->createElement('description'); 
$newCountryElement->appendChild($descElement); 

my $startElement= $doc->createElement('start'); 
my $startTextNode= $doc->createTextNode('1900'); 
$startElement->appendChild($startTextNode); 
$newCountryElement->appendChild($startElement); 

my $endElement= $doc->createElement('end'); 
$newCountryElement->appendChild($endElement); 

#add the country to the country-list 
$countryListElement->appendChild($newCountryElement); 

#print it out 
print $doc->toString; 

#print to file 
$doc->printToFile("out.xml"); 
+0

うわー、素晴らしいと理解しやすい作品:) - ありがとう。私が持っている問題は、ノードを追加すると、o/pがちょっと変わったように見えます。インデントとスペースは厄介です。それに対する解決策はありますか? – hari

+0

Aah、それは私のユーザー入力フィールドで追加された "\ n"の文字です。 "チャンプ"はそのトリックをやった。ありがとう。 – hari

0

プッシュは使用できません。プッシュは、項目を配列(リスト)に追加するためのものです。国はハッシュではなくリストで表されるので、あなたは何かを必要とします。

$ doc - > {国} - > {トランシルバニア} = {};

これは、 'Transylvania'の空のハッシュを作成しています。あなたのシステムではそこに何らかの構造が必要となるかもしれません。

+0

ありがとうコリン。 – hari

関連する問題