2

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')没有运气。

4

1 回答 1

4

该模块正在从您的呼叫XML::Twig::Elt中丢弃无关紧要的空白。inner_html

同时,您已经keep_spaces => 1XML::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>
于 2013-03-12T16:00:23.237 回答