2013-04-08 98 views
0

我有一個xml文檔,其中包含要放入數據庫的信息。例如:使用XML :: libXML解析xml - 獲得第n個子節點

<pc> 
    <name>John</name> 
    <last>Smith</last> 
    <address> 
     <business> 
      <street>987 Broad Way</street> 
      <city>New York</city> 
      <state>New York</state> 
     </business> 
     <home> 
      <street>123 Main St.</street> 
      <city>Jersey City</city> 
      <state>Nebraska</state> 
     </home> 
    </address> 
    <phone>123-456-7890</phone> 
</pc> 

我打算使用perl來解析這些數據來構建mysql語句。我有得到一個格式,與以下幾個問題:

name="John" 
last="Smith" 
... 

我使用至今的代碼是:

use strict; 
use warnings; 
use XML::LibXML; 

my $filename = "sample.xml"; 
my $parser = XML::LibXML->new(); 
my $xmldoc = $parser->parse_file($filename); 

for my $contact ($xmldoc->findnodes('/server')){ 
    print $contact->nodeName(),"\n"; 
    foreach my $child ($contact->findnodes('*')){ 
     print "\t", $child->nodeName(), ":\n"; 
     foreach my $grandchild ($child->findnodes('*')){ 
      print"\t\t", $grandchild->nodeName(), ":", $grandchild->textContent(), "\n"; 
     } 
    } 
} 

我不使用perl的不多,我不是太熟悉XML :: libXML庫(http://metacpan.org/pod/XML::LibXML)。我想我需要找到最後一個孩子,並以我的方式回到節點?我對於如何構建mysql的「插入」和「更新」有點失望。

+0

您的代碼與您的輸入和您聲明的期望輸出無關,儘管聲明您希望SQL,但它不是SQL。而你的頭銜表明希望找到第n個孩子,這對於給定的XML來說是完全不需要的。你能理解這一切嗎? – ikegami 2013-04-08 20:46:45

+0

對不起,我的想法是我會用perl來解析xml文件並建立sql語句並一次運行它們。 – Jeff 2013-04-09 00:52:46

回答

0

修改this code要經過所有的孩子。這是我完成的代碼:

my $nodes = $xml->findnodes('//*'); 
foreach my $node ($nodes->get_nodelist) { 
    my $children; 
    my $nodeSide = ($node->findnodes('*')->size); 
if ($nodeSize > 0){ 
printf "%n%s :\n", $node->localname; 
} 
else { 
printf "%s: %s\n", $node->localname, $node->textContent(); 
} 
} 

隨着輸出,我可以做這樣的事情,

插入到數據庫($節點 - >的textContent());

再次,這不是一個好的sql語句,但我會在以後的工作。重要的部分是節點分離和迭代。