在保留格式的同时从文件读取XML和文件

我使用这个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 &#xD;&#xA;test2&#xD;&#xA;test3&#xD;&#xA;" 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::ParserXML::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还应该留下编码,并且处理起来也要好得多.

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念