簡體   English   中英

如何使用 perl 中的 xml::libxml 檢索 xml 的所有節點?

[英]How to retrieve all the nodes of an xml using xml::libxml in perl?

我有一個像這樣的 xml 文件“file.xml

  <tables>
        <table>
                <name>abc</name>
                <row>12</row>
                <col>13</col>
        <table>
                <name>xyz</name>
                <IsWrapper/>
            <table>
                      <name>dummy</name>
                       <row>121</row>
                       <col>131</col>
            </table>
        </table>        
    </tables>

    I am using xml::libxml using perl. Here is the code.

# ----- Parsing config XML file ---
my $parser = XML::LibXML->new();
my $xmldoc = $parser->parse_file ("file.xml") || die("Could not parse xml file\n");
my $root = $xmldoc->getDocumentElement()|| die("Could not get Document Element \n");
print "\n root = $root \n";
if ($root->nodeType == ELEMENT_NODE) 
    {

        foreach my $child ($root->getChildNodes()) 
        { 
            #print "\n my child: $child \n";
            $st = $child->textContent;
            print "\n child name: $st \n";
            if ($child->nodeName eq 'table')
            {  
                $dc = $child->nodeName;
                print "\n node name is node: $dc\n";
                if (defined($child->getElementsByTagName('IsWrapper',0)->item(0)))
                { 
                    #do some thing
                }
                else
                {   
                    print "\n eneterd in else part\n";
                    #do some thing        
                }
            }
        }
    }

但我無法獲得主節點。 我只能得到這個結構。

<table>
            <name>xyz</name>
            <IsWrapper/>
        <table>
                  <name>dummy</name>
                   <row>121</row>
                   <col>131</col>
        </table>
    </table>    

我怎樣才能以相同的順序獲取結構中的所有元素。

output應該是這樣的

<tables>
<table><name>abc</name>
    <row>12</row>
    <col>13</col>
    <name>xyz</name>
        <row>121</row>
    <col>131</col>
        </table>
 </tables>  

如何使用 Perl 在 libxml 中解析上述 XML 並獲取以下 output?

非常感謝您的幫助。

這不是格式良好的XML 文檔。 你有三個開始的表格標簽,只有兩個結束。

您應該首先使用XML 驗證器檢查您的 XML 代碼。

我同意 AlexTheBird 的觀點。

如果您更改 xml 以獲得有效的統計信息,您將能夠解析該文件。 這個文件:

<tables>
    <table>
        <name>abc</name>
        <row>12</row>
        <col>13</col>
    </table>
</tables>

給我以下結果,使用 XML::Simple

$VAR1 = {
      'table' => {
                 'col' => '13',
                 'row' => '12',
                 'name' => 'abc'
               }
    };

暫無
暫無

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

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