【发布时间】:2011-09-01 17:15:33
【问题描述】:
我有一个类似“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>
如何使用 Perl 解析上述 XML 并在 libxml 中获取以下输出?
非常感谢您的帮助。
【问题讨论】: