2011-05-05 123 views
3

我正在使用XML :: LibXML(Ver:1.70)。使用XML遍歷節點:: LibXML

我的XML輸入文件看起來像這樣:

<?xml version="1.0" encoding="UTF-8"?> 
<Equipment xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <Equipments> 
    <ECID logicalName="SysNameAlpha" id="0"/> 
    <ECID logicalName="SysNameBeta" id="1"/> 
    </Equipments> 
</Equipment> 

和我的Perl腳本:

my $file = 'data.xml'; 
my $parser = XML::LibXML->new(); 
my $tree = $parser->parse_file($file); 
my $root = $tree->getDocumentElement; 

foreach my $camelid ($root->findnodes('Equipments')) { 
    my $name = $camelid->findvalue('ECID/@logicalName'); 
    my $id = $camelid->findvalue('ECID/@id'); 
    print $name; 
    print " = "; 
    print $id; 
    print ";\n"; 
} 

我得到的輸出是:

SysNameAlphaSysNameBeta = 01; 

但我想這樣的輸出:

SysNameAlpha = 0;  
SysNameBeta = 1; 

我該如何做到這一點?

回答

12

節點只有一個Equipments,因此您只能得到一個$camelid進行掃描。爲了補救,你可能會稍微改變一些東西,例如重複設備/ ECIDs:

foreach my $camelid ($root->findnodes('Equipments/ECID')) { 
    my $name = $camelid->findvalue('@logicalName'); 
    my $id = $camelid->findvalue('@id'); 
    ... 
}