在保留格式的同时从文件读取XML和文件
发布时间:2020-12-16 05:36:47 所属栏目:百科 来源:网络整理
导读:我使用这个perl代码从文件中读取 XML,然后写入另一个文件(我的完整脚本有代码来添加属性): #!usr/bin/perl -wuse strict;use XML::DOM;use XML::Simple;my $num_args = $#ARGV + 1;if ($num_args != 2) { print "nUsage: ModifyXML.pl inputXML outputXML
我使用这个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 outputXMLn"; 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还应该留下编码,并且处理起来也要好得多. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |