如何在perl中使用xml :: libxml检索xml的所有节点?

时间:2011-05-25 11:58:18

标签: xml perl

我有一个像这样的“file.xml

的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>    

如何以相同的顺序获取结构中的所有元素。

输出应该是这样的

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

如何解析上述XML并使用Perl在libxml中获取以下输出?

非常感谢帮助。

2 个答案:

答案 0 :(得分:1)

这不是well-formed XML文档。 你有三个开放表标签,只有两个关闭。

您应首先使用XML-Validator检查XML代码。

答案 1 :(得分:0)

我同意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'
               }
    };