【发布时间】:2016-11-03 23:09:01
【问题描述】:
我使用这个 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>
我怀疑我没有正确写入文件。
【问题讨论】:
-
当我想到“保留换行符”时,这根本不是我想到的。在这里,您希望保留恰好代表 CR/LF 字符的 编码。
-
看起来 XML::DOM 设置了一个默认处理程序来扩展所有内容(参见 DOM.pm 第 2054-58 行)。您是否尝试过摆弄它以获得您想要的 noexpand 行为?
-
XML::DOM 的那部分似乎不太正常 - 不过感谢您的建议