【发布时间】:2013-05-24 15:37:00
【问题描述】:
遇到包含巨大文本节点的xml数据文件后, 我在我的数据中寻找一些方法来阅读和评估它们 处理脚本。
xml 文件是用于分子建模的 3D 坐标文件 具有这种结构的应用程序(示例):
<?xml version="1.0" encoding="UTF-8"?>
<hoomd_xml version="1.4">
<configuration>
<position>
-0.101000 0.011000 -40.000000
-0.077000 0.008000 -40.469000
-0.008000 0.001000 -40.934000
-0.301000 0.033000 -41.157000
0.213000 -0.023000 -41.348000
...
... 300,000 to 500,000 lines may follow >>
...
-0.140000 0.015000 -42.556000
</position>
<next_huge_section_of_the_same_pattern>
...
...
...
</next_huge_section_of_the_same_pattern>
</configuration>
</hoomd_xml>
每个 xml 文件包含几个巨大的文本节点,大小在 60MB 到 100MB 之间,具体取决于内容。
我首先尝试了使用XML::Simple 的幼稚方法,但加载器最初解析文件需要很长时间:
...
my $data = $xml->XMLin('structure_80mb.xml');
...
并以“内部错误:巨大的输入查找”停止,因此这种方法不太实用。
下一次尝试是使用XML::LibXML 进行读取 - 但在这里,初始加载程序会立即退出并显示错误消息“解析器错误:xmlSAX2Characters:巨大的文本节点”。
在stackoverflow上写这个话题之前,我为自己写了一个q&d解析器并通过它发送文件(在将xx MB xml文件slurping到标量$xml之后):
...
# read the <position> data from in-memory xml file
my @Coord = xml_parser_hack('position', $xml);
...
将每一行的数据作为数组返回,几秒钟内完成,如下所示:
sub xml_parser_hack {
my ($tagname, $xml) = @_;
return () unless $xml =~ /^</;
my @Data = ();
my ($p0, $p1) = (undef,undef);
$p0 = $+[0] if $xml =~ /^<$tagname[^>]*>[^\r\n]*[r\n]+/msg; # start tag
$p1 = $-[0] if $xml =~ /^<\/$tagname[^>]*>/msg; # end tag
return () unless defined $p0 && defined $p1;
my @Lines = split /[\r\n]+/, substr $xml, $p0, $p1-$p0;
for my $line (@Lines) {
push @Data, [ split /\s+/, $line ];
}
return @Data;
}
到目前为止,这工作正常,但当然不能认为是“生产就绪”。
问:如何使用 Perl 模块读取文件?我会选择哪个模块?
提前致谢
rbo
附录:在阅读了 choroba 的评论后,我更深入地研究了 XML::LibXML。
打开文件my $reader = XML::LibXML::Reader->new(location =>'structure_80mb.xml'); 有效,与我之前的想法相反。如果我尝试访问标签下方的文本节点,则会出现错误:
...
while ($reader->read) {
# bails out in the loop iteration after accessing the <position> tag,
# if the position's text node is accessed
# -- xmlSAX2Characters: huge text node ---
...
【问题讨论】:
-
search.cpan.org/~mirod/XML-Twig-3.44/Twig.pm - 用于以树模式处理大量 XML 文档的 perl 模块。
-
您是如何使用 XML::LibXML 打开文件的?它适用于 100MB 的文件。
-
@choroba - 谢谢,我再次检查了 - 并更新了主题。
标签: xml perl xml-parsing