【问题标题】:Unable to update content in xml tag using XML::Twig无法使用 XML::Twig 更新 xml 标记中的内容
【发布时间】:2020-06-24 07:11:04
【问题描述】:

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

这是我的 xml 文件:-

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

代码sn-p:-

  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);

我必须将&lt;log&gt;false&lt;/log&gt; 更新为&lt;log&gt;true&lt;/log&gt;。我在这里错过了什么吗?

【问题讨论】:

    标签: perl xml-twig


    【解决方案1】:

    那是因为exit 退出了程序,所以永远不会到达print_to_file。移除出口。您可以将它们替换为 returns,但它们不是必需的。

    【讨论】:

      【解决方案2】:

      当我遇到这类事情时,我喜欢写一个类似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' ) },
      

      另外,我可能会考虑在 twig 处理程序之外执行任何 Perforce 魔法。在将文件交给 Twig 之前,先锁定文件。如果您无法获得该锁,则最好不要处理它。然后,记得稍后释放它。如果您将所有这些操作紧密结合在一起,您就不太可能忘记一个步骤。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-05-11
        • 2010-11-29
        • 2020-07-26
        • 2016-08-15
        • 2018-08-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多