perl xml dom中文乱码问题解决

来源:互联网 发布:c语言头文件 stdio.h 编辑:程序博客网 时间:2024/05/21 19:34

在linux服务器上,很容易出现中文乱码。

一般情况下,只要保持服务器环境是utf8,文件格式是utf8,用各种语言默认的读写文件方式通常不会出现乱码。

但是,在用perl xml dom写xml的时候就出现了这个问题。

perl xml dom默认应该是用ascii来读写文件,所以,对中文要先进行解码decode,再写入。

例如:

 1 #更新显示的xml文件 2 sub writeXml 3 { 4     my $projectList = "$hometouch_root/config/projectList.xml"; 5     my $parser = new XML::DOM::Parser ; 6     my $doc = $parser->parsefile($projectList); 7     XML::DOM::setTagCompression(sub{return 1});  8     my $newItem = $doc->createElement("item"); 9     #所以这里先将中文进行解码10     $newItem->setAttribute("name",decode("utf8",$projectChinese));11     $newItem->setAttribute("eng",$projectName);12     $newItem->setAttribute("version","");13     my $root = $doc->getElementsByTagName("projects")->[0];14     $root->appendChild($newItem);15     16     #write the file17     my $xml = ($doc->createXMLDecl('1.0','UTF-8')->toString).($root->toString) ;18     19     open my $myfd, ">", $projectList;20     print $myfd $xml ;21     close $myfd ;22     23     #xml tidy24     my $tidy_obj = XML::Tidy->new('filename' => $projectList);25     $tidy_obj->tidy();26     $tidy_obj->write();27 }

 

原创粉丝点击