1

I have a xml which i need to parse the xml and traverse till the last child , the XML will be dynamically generated so i do not know the depth of the XML , Can i iterate through the xml till its last child and siblings if any . Please help in resolving this issue :

My code snippet is :

            foreach my $childNodes ($root->findnodes('/'))
            {
                print $childNodes->nodePath;
                print "\n";
                if($childNodes->hasChildNodes)
                {
                    foreach my $gChildNode ($camelid->childNodes)
                    {
                      print $gChildNode->nodePath;
                      print "\n";
                    }
             }

This prints the node till depth 2 but if the depth is 3 i mean the root has one child and the child my code prints it but if there is another child here the code will not print and can not guess ..How can i find this .

Thanks in advance.

4

1 回答 1

6

只需包装代码以在函数中处理节点并递归调用它。带有一些附加注释的示例:

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);
于 2014-02-22T17:26:05.667 回答