无法使用 XML::Twig 更新 xml 标签中的内容

Unable to update content in xml tag using XML::Twig

我无法使用 xml Twig 模块更新 xml 标签中的内容。

这是我的 xml 文件 :-

<?xml version="1.0"?>
<test customerProprietary="false">
  <classes>
    <class name="new" />
  </classes>
  <chars>
    <log>false</log>
  </chars>
</test>

代码片段:-

  my $twig = XML::Twig->new(
     pretty_print => 'indented',
     twig_handlers => {
             log   => sub {
                             if ($_->text eq 'true'){
                               exit;
                             }
                             else{
                               print $_->text;
                               subp4open($xmlfile);
                               $_->set_text( 'true' );
                               exit;
                            }
       }
);

$twig->parsefile($script_path);
$twig->print_to_file($script_path);

我必须将 <log>false</log> 更新为 <log>true</log>。我在这里遗漏了什么吗?

那是因为 exit exits the program, so print_to_file is never reached. Remove the exits. You can replace them with returns,但不需要它们。

当我 运行 遇到这些事情时,我喜欢用 say "This far" 这样的语句来查看我是否已经到达代码的特定部分:

say "About to parse file";
$twig->parsefile($script_path);
say "About to print file";
$twig->print_to_file($script_path);

在您的处理程序中,有一些您可以改进的地方。由于您不想在值已经是 true 的情况下做任何事情,所以甚至不要考虑这种情况:

       log   => sub {
                         if ($_->text ne 'true'){
                           print $_->text;
                           subp4open($xmlfile);
                           $_->set_text( 'true' );
                        }
                 },

如果您希望它们全部为真,我可能倾向于始终更新值。我不在乎之前是什么,只要我最后得到我想要的东西(尽管这样可以稍微调整你的源代码控制):

       log   => sub { $_->set_text( 'true' ) },

此外,我可能会考虑在树枝处理程序之外执行任何 Perforce 魔法。在将文件交给 Twig 之前先锁定文件。如果你不能得到那个锁,你还不如不去处理它。然后,记得稍后释放它。如果您同时执行所有这些操作,您就不太可能忘记一个步骤。