XML的相关部分看起来像
<?xml version="1.0" encoding="UTF-8"?>
<key name="home">
<entry name="default">zzzzz</entry>
<key name="ffffff"></key>
<key name="plugin">
<key name="pst">
<entry name="enable">true</entry>
</key>
</key>
<key name="hover">
<key name="doze">
<key name="eventmanager">
<key name="types"></key>
</key>
<key name="ips">
<key name="proto">
<key name="dos">
<key name="dop"></key>
</key>
</key>
</key>
</key>
</key>
.
.
.
我的代码:
#!/root/bin/perl
use strict;
use warnings;
use XML::Twig;
my $tree = XML::Twig->new(pretty_print => 'indented', keep_spaces => 1);
$tree->parsefile(shift);
my $msg =<<'MSG';
<key name="absy">
<entry name="msg"></entry>
<entry name="title"></entry>
</key>
MSG
my $client_plugin = XML::Twig::Elt->new( key => { name => 'client' } )->set_inner_xml($msg);
$client_plugin->paste(last_child => $tree->first_elt(sub { $_[0]->tag =~ m/key/ and $_[0]->att('name') =~ m/plugin/i }));
$tree->print;
问题是添加的元素出现在一行中,而不是像其他元素那样真正缩进。
我也试过$tree->print(pretty_print => 'indented')
而没有运气。
答案 0 :(得分:4)
XML::Twig::Elt
模块正在丢弃inner_html
来电中无关紧要的空白。
同时,您已为keep_spaces => 1
模块指定了XML::Twig
,因此它保留了(缺少)空格。
删除keep_spaces => 1
,它应该适合您。
<强>更新强>
您可能希望查看与您自己的程序执行相同操作的代码,但使用XPath步骤作为条件而不是不太可读的匿名子例程。
use strict;
use warnings;
use XML::Twig;
my $tree = XML::Twig->new(pretty_print => 'indented');
$tree->parsefile(shift);
my $msg = <<'MSG';
<key name="absy">
<entry name="msg"/>
<entry name="title"/>
</key>
MSG
my $client_plugin = XML::Twig::Elt->new( key => { name => 'client' } );
$client_plugin->set_inner_xml($msg);
my $plugin = $tree->first_elt('key[@name="plugin"]');
$client_plugin->paste(last_child => $plugin);
$tree->print;
<强>输出强>
<?xml version="1.0" encoding="UTF-8"?>
<key name="home">
<entry name="default">zzzzz</entry>
<key name="ffffff"></key>
<key name="plugin">
<key name="pst">
<entry name="enable">true</entry>
</key>
<key name="client">
<key name="absy">
<entry name="msg"/>
<entry name="title"/>
</key>
</key>
</key>
<key name="hover">
<key name="doze">
<key name="eventmanager">
<key name="types"></key>
</key>
<key name="ips">
<key name="proto">
<key name="dos">
<key name="dop"></key>
</key>
</key>
</key>
</key>
</key>
</key>