簡體   English   中英

使用XML :: libXML解析xml-獲取第n個子節點

[英]Using XML::libXML to parse xml--get nth Child Node

我有一個xml文檔,其中包含要放入數據庫中的信息。 例:

<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構建“插入”和“更新”。

修改此代碼以遍歷所有子代。 這是我完成的代碼:

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();
}
}

有了輸出,我可以做類似的事情,

插入數據庫($ node-> textContent());

再次,那不是一個好的sql語句,但是我稍后會處理。 重要的部分是節點分離和迭代。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM