且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Perl从目录中的多个XML文件创建一个XML文件

更新时间:2022-11-28 19:28:39

首先,感谢您在这里发表您的努力并说明最终要做什么,即将所有XML合并到一个文件中.

First of all, thank you for posting your effort here and for stating what you ultimately want to do, which is combine all XMLs into a single file.

要解决问题的需求:

  1. use strict; use warnings;

捕捉愚蠢的错误并实施良好的错误处理

To catch silly mistakes and enforce good error handling

use XML::LibXML;

使用解析器

my @xml_files = glob '*.xml';

找到目录中的所有XML文件

Find all XML files in your directory

my $bigXML = XML::LibXML::Document->new( '1.0', 'UTF-8');

实例化将存储所有节点的大型XML.

Instantiate big XML where all nodes will be stored.

遍历每个文件,获取节点并将其推送到聚合节点

Loop over each file, get the node and push the node into an aggregated node

我的$总计; 为我的$ xml_file(@xml_files){

my $aggregated; for my $xml_file ( @xml_files ) {

my $doc = XML::LibXML->new->parse_file( $xml_file );

my ( $specNode ) = $doc->findnodes( '//specification' );

if ( ! $aggregated ) {        # Initialize if doesn't exist

    $aggregated = $specNode;
}

else {                        # Add more <details>

    my @details = $specNode->findnodes( './details' );
    $aggregated->addChild( $_ ) foreach @details;
}

}

$aggregated节点添加到$bigXML文档中并打印:

Add the $aggregated node to the $bigXML document and print:

$bigXML->addChild( $aggregated ); $bigXML->toFile( 'aggregated_data.xml' );

$bigXML->addChild( $aggregated ); $bigXML->toFile( 'aggregated_data.xml' );