Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PerlXML::细枝-在属性中及其周围保留引号_Perl_Quotes_Double Quotes_Xml Twig - Fatal编程技术网

PerlXML::细枝-在属性中及其周围保留引号

PerlXML::细枝-在属性中及其周围保留引号,perl,quotes,double-quotes,xml-twig,Perl,Quotes,Double Quotes,Xml Twig,我正在选择性地修复一些元素和属性。不幸的是,我们的输入文件包含单引号和双引号属性值。此外,某些属性值包含引号(在值内) 使用XML::Twig,我看不出如何保留属性值周围存在的任何引号 下面是示例代码: use strict; use XML::Twig; my $file=qq(<file> <label1 attr='This "works"!' /> <label2 attr="This 'works'!" /> </file> )

我正在选择性地修复一些元素和属性。不幸的是,我们的输入文件包含单引号和双引号属性值。此外,某些属性值包含引号(在值内)

使用XML::Twig,我看不出如何保留属性值周围存在的任何引号

下面是示例代码:

use strict;
use XML::Twig;

my $file=qq(<file>
  <label1 attr='This "works"!' />
  <label2 attr="This 'works'!" />
</file>
);

my $fixes=0; # count fixes
my $twig = XML::Twig->new( twig_handlers => { 
                             '[@attr]' => sub {fix_att(@_,\$fixes);} },
                             # ...
                           keep_atts_order => 1,
                           keep_spaces => 1,
                           keep_encoding => 1, );
#$twig->set_quote('single');

$twig->parse($file);
print $twig->sprint();

sub fix_att {
  my ($t,$elt,$fixes) =@_;
  # ...
}
然后我们会看到label2的XML无效:

<label2 attr='This 'works'!' />


是否有保留现有报价的选项?或者有没有更好的方法来选择性地固定树枝?

您使用
保持编码的具体原因是什么?如果没有它,报价将被正确编码


keep_encoding
用于保留文件的原始编码,但还有其他方法可以做到这一点。它主要用于5.8之前的时代,当时的编码不像现在那么流畅。

问题仍然存在于3.44中。作为一种解决方法,我添加了一个额外的细枝处理程序,将属性值中的所有双引号更改为单引号:
'*'=>sub{my($t,$elt)=@;foreach(key%{$elt->atts}{${$elt->atts}{${$u}=~ s/\'/\'/g;},
我确实需要保留原始编码。Mirod,你能建议一种替代方法来保留编码吗?谢谢。尝试执行
binmode STDOUT,sprintf(“编码(:%s)”,$twig->encoding)
在打印细枝之前。这应该将STDOUT的编码设置为正确的值。尽管测试它,因为我不能100%确定Perl支持所有XML编码。
$twig->set_quote('single');
<label2 attr='This 'works'!' />