在保留格式的同时从文件读取XML并向文件读取XML [英] read XML from and to file while preserving format

查看:111
本文介绍了在保留格式的同时从文件读取XML并向文件读取XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下perl代码从文件中读取XML,然后写入另一个文件(我的完整脚本具有添加属性的代码):

I use this perl code to read XML from a file, and then write to another file (my full script has code to add attributes):

#!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:

however this doesn't preserve characters like line breaks. For example, this 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>

我怀疑我没有正确写入文件.

I suspect I'm not writing to file properly.

推荐答案

使用例如XML :: LibXML .涉及的主要模块是 XML: :LibXML :: Parser XML :: LibXML :: DOM (以及其他).返回的对象通常是 XML :: LibXML :: Document

Use XML::LibXML, for example. The main modules that get involved are XML::LibXML::Parser and XML::LibXML::DOM (along with others). The returned object is generally 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上的方法来设置编码(例如).

We don't have to first create an object but can directly say XML::LibXML->load_xml. I do it as an example since this way one can then use methods on $reader to set up encodings (for example), before parsing but outside of the constructor.

此模块也更方便处理.

This module is also far more convenient for processing.

XML :: Twig 也应离开编码,而且处理起来也要好得多.

The XML::Twig should also leave encodings, and is also far better for processing.

这篇关于在保留格式的同时从文件读取XML并向文件读取XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆