在子例程中使用子节点(XML :: LibXML)

时间:2014-11-04 13:15:08

标签: xml perl

在我的一小段代码中,我解析了一些XML数据,但由于我需要在3个地方做同样的事情,所以我想每次都做一个子程序。但我需要将当前节点作为参数传递,超出了我当前访问当前节点的子节点的技能。

以下是我的代码示例:

foreach $day ($doc->findnodes('/my/current/path')) {

  @atts = $day->getAttributes();

  foreach $at (@atts) {

    $na = $at->getName();
    $va = $at->getValue();

    if ($va eq "today") {

      #------ my repeated code begins here -----
      foreach $thing ($day->findnodes('child_nodes_im_looking_for')) {

        #----- do a lot of stuff
      }

      #------ my repeated code ends here -----
    }

    if ($va eq "tomorrow") {

      #same repeated code
    }

    if ($va eq "some_other_day") {

      #same repeated code.... again
    }

    #for other days... do nothing

  }

我应该如何将当前节点传递给子例程,以便直接从例程访问其子节点?

1 个答案:

答案 0 :(得分:3)

我相信你有use strictuse warnings生效吗?即使你有,你应该尽可能地将my声明为 late ,理想情况是在他们的第一个使用点。

我不清楚问题究竟是什么,从表面上看,你只需要将节点$day作为正常的子例程参数传递。

您的代码示例的重构显示了这个想法。如果我误解了你,请说出来。

for my $day ($doc->findnodes('/my/current/path')) {

  my @atts = $day->getAttributes();

  for my $att (@atts) {

    my $na = $att->getName;
    my $va = $att->getValue;

    if ($va eq 'today') {
      repeated_code($day);
    }

    if ($va eq 'tomorrow') {
      repeated_code($day);
    }

    if ($va eq 'some_other_day') {
      repeated_code($day);
    }

    # for other days... do nothing

  }
}

sub repeated_code {
  my ($node) = @_;

  for my $thing ($node->findnodes('child_nodes_im_looking_for')) {

    #----- do a lot of stuff
  }

}
相关问题