我有以下XML:
< measCollecFile>
< fileHeader>
< measCollec beginTime="2013-03-14T12:10:00+00:00" />
</ fileHeader>
< measData>
< measInfo>
< granPeriod duration="PT300S" endTime="2013-03-14T12:15:00+00:00" />
< measType>VS.ave</measType>
< measType>VS.aveCPU</measType>
< measValue>VS1</measValue>
< measValue>VS2</measValue>
</ measInfo>
</ measData>
</ measCollecFile>
问:我的问题我需要处理这个XML文件并修改某些元素中的少量数据。我可以在这个网站的帮助下做到这一点,你可以从我以前的帖子中看到。
有一个新的挑战。正如您所看到的,XML中也有datetime元素。我需要以与XML中显示的格式相同的格式将其更新为当前日期时间。即XML将始终包含任何日期,我只是找到datetime标记并将其更新为当前日期时间,但它应该与它在那里的格式相同。
我应该将其视为单独的问题并将其视为简单的正则表达式Perl问题,并相应地解析为平面文件查找和替换问题?
或 LIBXML 内置了什么来识别日期时间标记并使用最新日期时间更新它?
答案 0 :(得分:1)
没有什么特别可以识别“datetime”标签。你当然可以寻找适合特定格式的属性,但这真的是你想要的吗?
使用XML::LibXML
和Time::Piece
将beginTime替换为当前日期:
use strict;
use warnings;
use XML::LibXML;
use Time::Piece;
my $date_format = '%Y-%m-%dT%H:%M:%S';
my $data = do { local $/; <DATA> };
my $dom = XML::LibXML->load_xml(string => $data);
for my $node ($dom->findnodes('//*[@beginTime]')) {
if ( my $begin = $node->getAttribute('beginTime') ) {
my ($plaindate, $tz) = split '(?=\+)', $begin;
my $date = Time::Piece->strptime($plaindate, $date_format);
print "old beginTime = '$date'\n";
my $newdate = localtime->strftime($date_format);
$node->setAttribute('beginTime', $newdate . $tz);
}
}
print $dom->toString();
__DATA__
<measCollecFile>
<fileHeader>
<measCollec beginTime="2013-03-14T12:10:00+00:00" />
</fileHeader>
<measData>
<measInfo>
<granPeriod duration="PT300S" endTime="2013-03-14T12:15:00+00:00" />
<measType>VS.ave</measType>
<measType>VS.aveCPU</measType>
<measValue>VS1</measValue>
<measValue>VS2</measValue>
</measInfo>
</measData>
</measCollecFile>
要更新beginTime和endTime,您可以创建更复杂的xpath:
my @attribs = qw(beginTime endTime);
my $attribs_list = join ' | ', map {'@'.$_} @attribs;
for my $node ($dom->findnodes("//*[$attribs_list]")) {
for my $key (@attribs) {
if ( my $att = $node->getAttribute($key) ) {
my ($plaindate, $tz) = split '(?=\+)', $att;
my $date = Time::Piece->strptime($plaindate, $date_format);
print "old $key = '$date'\n";
my $newdate = localtime->strftime($date_format);
$node->setAttribute($key, $newdate . $tz);
}
}
}