【发布时间】:2013-09-23 13:34:08
【问题描述】:
在 Perl 中,我使用 XML::Twig 来读取 XML 文件。一些属性的文本如下所示:
<p>Here is some text.</p>

<p>Some more text.
我正在将此属性读入名为$Body 的变量中。我想将此变量打印到文件中而不插入字符串中的特殊字符,即输出应该看起来与输入完全相同。我的代码如下:
open (my $OUT, ">", "out.csv") or die $!;
print $OUT $Body;
但是,当我查看 out.csv 时,我看到:
<p>Here is some text.</p>
<p>Some more text.
相反,我想查看原始字符串:
<p>Here is some text.</p>
&;#xA;<p>Some more text.
我尝试了以下方法但没有成功:
-
print $OUT '$Body';不起作用,只显示“$Body” -
print $OUT "$Body";不起作用,和没有引号一样。 -
print $OUT qw{$Body};不起作用,只显示“$Body”。这是一个完整的例子:
tmp.xml
<?xml version="1.0" encoding="utf-8"?>
<root>
<node Body="<p>Here is some text.</p>

<p>Some more text."/>
</root>
代码:
#!/usr/bin/perl
use strict;
use XML::Twig;
my $t=XML::Twig->new();
$t->parsefile("tmp.xml");
my $root= $t->root;
open (my $OUT, ">", "out.csv") or die();
my @nodes = $root->children('node'); # get the para children
foreach my $node (@nodes){
my $Body = $node->{'att'}->{'Body'};
print $OUT $Body;
}
结果:
[dev@mogli:/swta] $ ./script.pl
[dev@mogli:/swta] $ cat out.csv
<p>Here is some text.</p>
<p>Some more text.
【问题讨论】:
-
你确定你没有在转换文件中查看文件吗?它可能工作正常。
-
@Ian:我正在使用 vim 查看文件,它不会转换这些字符。
标签: perl xml-twig string-interpolation