在子例程(XML :: LibXML)中处理子节点

奥基

在我的一小段代码中,我解析了一些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

  }

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

鲍罗丁

我相信您拥有use strictuse warnings有效吗?即使有,也应该my尽可能声明变量,最好是在它们的第一个使用点。

我不清楚问题到底是什么,从表面上看,您只需要将节点$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
  }

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章