通过Perl脚本更改XML文件内容 [英] Change an XML file content via Perl script

查看:162
本文介绍了通过Perl脚本更改XML文件内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此线程是 Perl脚本填充XML的延续文件 .

This thread is in continuation of Perl script to populate an XML file.

我要更改的文件是:

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

我想在此列表中添加一个新国家.

I want to add a new country here in this list.

在上一个问题中, Perl脚本可填充XML文件 .

In previous question, 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';

建议添加一个新标签,但是在我的情况下,我不确定如何使用"push".我无法映射到正确的标签.

This was suggested to add a new tag, but in my case not sure how exactly can I use "push". I am not able to map to the correct tag.

推荐答案

我发现 XML :: DOM 易于使用.可能有些冗长,但您可以轻松了解它的功能.

I find XML::DOM a lot simpler to use. It may be a bit verbose, but you can easily understand what it is doing.

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");

这篇关于通过Perl脚本更改XML文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆