2010-11-29 3 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

아아, 사용자 입력 필드에 "\ n"문자가 추가되었습니다. "chomp"가 트릭을했습니다. 감사합니다 Dogbane. – hari

0

푸시를 사용할 수 없습니다. 푸시는 배열 (목록)에 항목을 추가하기위한 것입니다. 누군가가 전에 준 "밀기"명령으로 판단하면 국가는 목록이 아닌 해시로 표시되므로

$ doc -> {국가} -> {국가} -> {Transylvania} = {};

'Transylvania'의 빈 해시가 생성됩니다. 시스템에 거기에 어떤 구조가 있어야 할 수도 있습니다.

+0

감사합니다. Colin. – hari

관련 문제