2

このスレッドは、XMLファイルにデータを入力するためのPerlスクリプトの続きです。

変更したいファイルは次のとおりです。

<?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>

このリストに新しい国を追加したいと思います。

前の質問では、XMLファイルにデータを入力するためのPerlスクリプト

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

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

4

2 に答える 2

2

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");
于 2010-11-29T13:56:37.240 に答える
0

プッシュは使用できません。プッシュは、アイテムを配列(リスト)に追加するためのものです。誰かが以前にあなたに与えた「プッシュ」コマンドから判断すると、国はリストではなくハッシュとして表されるので、次のようなものが必要です

$ doc-> {countries)-> {country}-> {Transylvania} = {};

これは、「Transylvania」の空のハッシュを作成しています。システムでは、そこに何らかの構造が必要な場合があります。

于 2010-11-29T13:03:18.450 に答える