2009-06-08 99 views
3

我想用xPath解析XML文件。获得节点后,我可能需要在其父节点上执行xPath搜索。我使用XML::XPath当前的代码是:如何使用XML :: XPath获取父节点?

my $xp = XML::XPath->new(filename => $XMLPath); 
# get all foo or foos node with a name 
my $Foo = $xp->find('//foo[name] | //foos[name]'); 
if (!$Foo->isa('XML::XPath::NodeSet') || $Foo->size() == 0) { 
    # no foo found 
    return undef; 
} else { 
    # go over each and get its bar node 
    foreach my $context ($Foo->get_nodelist) { 
     my $FooName = $context->find('name')->string_value; 
     $xp = XML::XPath->new(context => $context); 
     my $Bar = $xp->getNodeText('bar'); 
     if ($Bar) { 
      print "Got $FooName with $Bar\n"; 
     } else { 
      # move up the tree to get data from parent 
      my $parent = $context->getParentNode; 
      print $parent->getNodeType,"\n\n"; 
     } 
    } 
} 

我的目标是获得FOO元素名称的哈希和他们的栏子节点的值,如果FOO没有一个杆节点就应该从其父FOO中的一个或foos节点。

对于这个XML:

<root> 
    <foos> 
     <bar>GlobalBar</bar> 
     <foo> 
      <name>number1</name> 
      <bar>bar1</bar> 
     </foo> 
     <foo> 
      <name>number2</name> 
     </foo> 
    </foos> 
</root> 

我希望:

number1->bar1 
number2->GlobalBar 

当试图获得父节点在使用上面的代码我得到一个错误:

灿” t调用方法“getNodeType”在 未定义值

任何帮助将不胜感激!

回答

4

正如查斯所提到的,你不应该创建第二个XML :: XPath对象(该文档提到这太)。您可以传递上下文作为find *方法的第二个参数,或者只需调用上下文节点上的方法,就像事实上获得$ FooName一样。

您还有几个方法调用不会做您认为的操作(getNodeType不返回元素名称,而是表示节点类型的数字)。

总体低于更新的代码似乎给你想要的东西:

#!/usr/bin/perl 

use strict; 
use warnings; 

use XML::XPath; 

my $xp = XML::XPath->new(filename => "$0.xml"); 
# get all foo or foos node with a name 
my $Foo = $xp->find('//foo[name] | //foos[name]'); 
if (!$Foo->isa('XML::XPath::NodeSet') || $Foo->size() == 0) { 
    # no foo found 
    return undef; 
} else { 
    # go over each and get its bar node 
    foreach my $context ($Foo->get_nodelist) { 
     my $FooName = $context->find('name')->string_value; 
     my $Bar = $xp->findvalue('bar', $context); # or $context->findvalue('bar'); 
     if ($Bar) { 
       print "Got $FooName with $Bar\n"; 
     } else { 
       # move up the tree to get data from parent 
       my $parent = $context->getParentNode; 
       print $parent->getName,"\n\n"; 
     } 
    } 
} 

最后,提醒一句:XML::XPath没有得到很好的维护,你会使用XML::LibXML反而可能会更好。代码将非常相似。

5

当您尝试调用undef上的方法时,您会看到该错误。在undef上调用方法的最常见原因是无法检查构造函数方法是否成功。更改

$xp = XML::XPath->new(context => $context); 

$xp = XML::XPath->new(context => $context) 
    or die "could not create object with args (context => '$context')"; 
+0

感谢您的回答,但这不是问题。我知道我得到错误消息试图调用一个undef的方法,问题是我在做什么错了 - 为什么我不能得到父节点?顺便说一句,构造函数是好的,我用你的代码,并没有消息。 – Dror 2009-06-08 13:59:45

+2

Offhand,我会说你的问题是,你正在通过分配$ xp第二次销毁原始对象。 – 2009-06-08 14:47:23