我使用这个 perl 代码从一个文件中读取 XML,然后写入另一个文件(我的完整脚本有添加属性的代码):
#!usr/bin/perl -w
use strict;
use XML::DOM;
use XML::Simple;
my $num_args = $#ARGV + 1;
if ($num_args != 2) {
print "\nUsage: ModifyXML.pl inputXML outputXML\n";
exit;
}
my $inputPath = $ARGV[0];
my $outputPath = $ARGV[1];
open(inputXML, "$inputPath") || die "Cannot open $inputPath \n";
my $parser = XML::DOM::Parser->new();
my $data = $parser->parsefile($inputPath) || die "Error parsing XML File";
open my $fh, '>:utf8', "$outputPath" or die "Can't open $outputPath for writing: $!\n";
$data->printToFileHandle($fh);
close(inputXML);
但是这不会保留换行符等字符。例如,这个 XML:
<?xml version="1.0" encoding="utf-8"?>
<Test>
<Notification Content="test1 testx 
test2
test3
" Type="Test1234">
</Notification>
</Test>
变成这样:
<?xml version="1.0" encoding="utf-8"?>
<Test>
<Notification Content="test1 testx
test2
test3
" Type="Test1234">
</Notification>
</Test>
我怀疑我没有正确写入文件。
最佳答案
使用XML::LibXML , 例如。涉及的主要模块是XML::LibXML::Parser和 XML::LibXML::DOM (与其他人一起)。返回的对象一般为XML::LibXML::Document
use warnings 'all';
use strict;
use XML::LibXML;
my $inputPath = 'with_encodings.xml';
my $outputPath = 'keep_encodings.xml';
my $reader = XML::LibXML->new();
my $doc = $reader->load_xml(location => $inputPath, no_blanks => 1);
print $doc->toString();
my $state = $doc->toFile($outputPath);
我们不必先创建一个对象,而是可以直接说XML::LibXML->load_xml
。我以它为例,因为这样一来,人们就可以在解析之前但在构造函数之外使用 $reader
上的方法来设置编码(例如)。
这个模块也更方便处理。
XML::Twig也应该留下编码,并且也更利于处理。
关于xml - 在保留格式的同时从文件读取 XML 和从文件读取 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40412736/