我有像这样的简单XML。
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<TCXML format="low_level" authKey="12345">
<Dataset acl_bits="0" creation_date="2019-04-03T13:42:47Z" dataset_type="#id6" island_id="4" elemId="id2478" last_mod_date="2019-04-03T13:49:31Z" />
<Dataset acl_bits="0" creation_date="2019-04-03T13:42:47Z" dataset_type="#id61" island_id="41" elemId="id2479" format_used="ASCII" last_mod_date="2019-04-03T13:49:31Z" />
</TCXML>
我正在使用Perl更改last_mod_date并重新保存xml文件。
当我尝试此Perl代码时,出现以下错误。
use strict;
use warnings;
use Data::Dump qw(dump);
use XML::LibXML;
use XML::LibXML::NodeList;
use XML::Simple;
use Data::Dumper;
print "Perl Starting ... \n\n";
open my $xmlfilename, '<', 'test100.xml' or die "No input Filename Found ... \n";
my $dom = XML::LibXML->load_xml(IO => $xmlfilename);
print "Looping Dataset ... \n\n";
foreach my $xmlNode ($dom->findnodes('//Dataset'))
{
my $last_mod_date = $xmlNode->find('./@last_mod_date');
print "last_mod_date: $last_mod_date ... \n";
#change dates
$last_mod_date->setData("2019-04-11");
#save xml file - can this be done at the very end?
$dom->toFile('test100.xml');
}
print "\nPerl End ... \n\n";
输出:
Perl Starting ...
Looping Dataset ...
last_mod_date: 2019-04-03T13:49:31Z ...
Can't locate object method "setData" via package "XML::LibXML::NodeList" at test100.pl line 26.
我已经搜索了Stack Overflow和Google。我仔细阅读了this post,但仍然感到困惑。我在做什么错了?
答案 0 :(得分:3)
对于将来遇到此问题的任何人,这就是我如何使其工作的方式。技巧是setValue
foreach my $xmlNode ($dom->findnodes('//Dataset'))
{
my ($last_mod_date) = $xmlNode->findnodes('./@last_mod_date');
print "last_mod_date: $last_mod_date ... \n";
#change dates
$last_mod_date->setValue('2019-04-11');
}
#save xml file at the very end
$dom->toFile('test100.xml');