递归遍历PerlXML::LibXML中的XML节点
我有一个xml,我需要解析xml并遍历到最后一个子项,xml将动态生成,因此我不知道xml的深度,我可以遍历xml直到它的最后一个子项和兄弟项(如果有的话)。请帮助解决此问题: 我的代码片段是:递归遍历PerlXML::LibXML中的XML节点,xml,perl,xml-libxml,Xml,Perl,Xml Libxml,我有一个xml,我需要解析xml并遍历到最后一个子项,xml将动态生成,因此我不知道xml的深度,我可以遍历xml直到它的最后一个子项和兄弟项(如果有的话)。请帮助解决此问题: 我的代码片段是: foreach my $childNodes ($root->findnodes('/')) { print $childNodes->nodePath; print "\n";
foreach my $childNodes ($root->findnodes('/'))
{
print $childNodes->nodePath;
print "\n";
if($childNodes->hasChildNodes)
{
foreach my $gChildNode ($camelid->childNodes)
{
print $gChildNode->nodePath;
print "\n";
}
}
这将打印节点直到深度2,但如果深度为3,我的意思是根有一个子节点,子节点我的代码将打印它,但如果这里有另一个子节点,代码将不会打印,也无法猜测..我如何找到它
提前感谢。只需将处理函数中节点的代码包装起来,然后递归调用即可。带有一些附加注释的示例:
sub process_node {
my $node = shift;
print $node->nodePath, "\n";
# No need to check hasChildNodes. If there aren't any
# children, childNodes will return an empty array.
for my $child ($node->childNodes) {
# Call process_node recursively.
process_node($child);
}
}
# documentElement is more straight-forward than findnodes('/').
process_node($root->documentElement);
只需将处理函数中节点的代码包装起来,然后递归调用它。带有一些附加注释的示例:
sub process_node {
my $node = shift;
print $node->nodePath, "\n";
# No need to check hasChildNodes. If there aren't any
# children, childNodes will return an empty array.
for my $child ($node->childNodes) {
# Call process_node recursively.
process_node($child);
}
}
# documentElement is more straight-forward than findnodes('/').
process_node($root->documentElement);
答案在你的标题中:你需要递归。答案在你的标题中:你需要递归。请找到我的代码片段作为我问题的答案…谢谢你的回答。@SriSri StackOverflow不像一个有线程的讨论论坛。如果您需要更多帮助,您应该打开一个新问题。非常感谢您的更新。。我想另一种方式..将开始新的讨论。请找到我的代码片段作为我问题的答案…谢谢你的回答..@SriSri StackOverflow不像一个有线程的讨论论坛。如果您需要更多帮助,您应该打开一个新问题。非常感谢您的更新。。我想另一种方式会开始新的讨论。