2012-02-27 85 views
0

我是XPath新手,想知道如何提取XML文檔中的值。Perl Xpath ::如何提取所有屬性值和屬性所屬元素的名稱

我有一個XML:

<root> 
<element1 attrib1 = value1 attrib2 = value2 > 
<element2 attrib1 = value1 attrib2 = value2 > 
<element3 attrib1 = value1 attrib2 = value2 > 
</root> 

我想要做的是非常久遠提取的元素名稱的所有屬性=值對。例如: element1 attrib1 value1 element2 attrib2 value2 。 。 element3 attrib2 value2

我試過使用'//@*' XPath查詢,它返回attrib = value,而不是elt名稱。

任何想法?

謝謝!

+0

您可以使用一個工具,如可視化的XPath(http://www.huttar.net/dimitre/XPV/TopXML-XPV.html)快速學習的XPath,玩,對不同的XPath表達式試驗任何想要的XML文檔。所選節點在XML文檔中內聯突出顯示。還介紹了不是節點的評估結果。 – 2012-02-27 18:24:24

+0

我使用過這個:http://chris.photobooks.com/xml/default.htm :) – krish7919 2012-02-29 11:23:44

+0

Krish:您使用的是缺乏XPath Visualizer功能的2/3ds,而且相當難看且不方便。它根本不接受大量的XPath表達式。嘗試'count(// *)'。 :) – 2012-02-29 14:19:40

回答

1

你可以使用'*/*'查找第二級的所有元素。

my $xp = XML::XPath->new(ioref => \*DATA); 

# select the element nodes without having to specify their names 
my @element_nodes = $xp->findnodes('*/*'); 

foreach my $element (@element_nodes) { 
    # see https://metacpan.org/module/XML::XPath::Node::Element 
    print $element->getName; 
    foreach my $attribute ($element->getAttributes) { 
     # see https://metacpan.org/module/XML::XPath::Node::Attribute 
     print ' '.$attribute->getName.' '.$attribute->getData; 
    } 
    print "\n"; 
} 

__DATA__ 
<root> 
<element1 attrib1="value1" attrib2="value2" /> 
<element2 attrib1="value1" attrib2="value2" /> 
<element3 attrib1="value1" attrib2="value2" /> 
</root> 
+0

print $ element-> getName; 只有一行..!這就是我想要的。 – krish7919 2012-02-27 10:31:09

1

要從你需要做以下的XML文件中提取值,

use XML::XPath; 

my $i; 

#specify the file name 

my $xpath = XML::XPath->new(filename => "file.xml"); 

# Now you can traverse through the nodes and get the atrributes 

$i = $xp->find('/root/element1')->get_node(1); 

# store the extracted values in an array 

push @attrib1, sprintf($i->getAttribute('attrib1')); 

push @attrib2, sprintf($i->getAttribute('attrib2')); 

$i = $xp->find('/root/element2')->get_node(1); 

push @attrib1, sprintf($i->getAttribute('attrib1')); 

push @attrib2, sprintf($i->getAttribute('attrib2')); 

END

請參閱此爲更多細節的Xpath

http://search.cpan.org/~msergeant/XML-XPath-1.13/XPath.pm

+0

其實,我下載XPath模塊只是爲了研究這些例子.. :)它爲我嘲笑,謝謝! – krish7919 2012-02-27 10:32:46

相關問題