【问题标题】:Perl XML::Twig - preserving quotes in and around attributesPerl XML::Twig - 在属性中和属性周围保留引号
【发布时间】:2013-06-01 14:36:12
【问题描述】:

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

使用 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) =@_;
  # ...
}

上面的代码为label1返回了无效的XML:

<label1 attr="This "works"!" />

如果我添加:

$twig->set_quote('single');

然后我们会看到 label2 的 XML 无效:

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

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

【问题讨论】:

  • 问题在 3.44 中仍然存在。作为一种解决方法,我添加了一个额外的 twig_handler 以将属性值内的所有双引号更改为单引号:'*' =&gt; sub {my ($t,$elt) =@_; foreach (keys %{$elt-&gt;atts}) {${$elt-&gt;atts}{$_} =~ s/\"/\'/g;}},

标签: perl quotes double-quotes xml-twig


【解决方案1】:

您使用keep_encoding 有什么特别的原因吗?没有它,报价将被正确编码。

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

【讨论】:

  • 我确实需要保留原始编码。 Mirod,您能建议一种替代方法来保留编码吗?谢谢。
  • 在打印树枝之前尝试做binmode STDOUT, sprintf( "encoding( :%s)", $twig-&gt;encoding);。这应该将 STDOUT 的编码设置为正确的值。不过测试一下,因为我不能 100% 确定 Perl 支持所有 XML 编码。
猜你喜欢
  • 2014-12-27
  • 2014-12-18
  • 2013-08-24
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多