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.

有帮助吗?

解决方案

Just wrap the code to process a node in a function and call it recursively. Example with some additional comments:

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top