Search code examples
perlxmldom

Perl XML:DOM - Getting children at specific depth


I'm doing some XML parsing using Perl and decided on XML::DOM. Assume I'm parsing a file containing the following:

<document>
   <A>
      <B/>
      <B/>
   </A>
   <B/>
</document>

The "B" element is processed differently depending on its relative location in the document (i.e. a B whose parent is A is different from a B whose parent is document). From a reference to to the document node, is it possible to get the B's that are immediate children. Then later, get a reference to the A node to get only the its child B's?

Thanks,

Andrew


Solution

  • Assuming that you know that all B elements will be children of either the document or an A, you can use the optional recurse parameter to getElementsByTagName. Passing 0 means to return only direct child elements:

    my @docB = $doc->getElementsByTagName('B', 0);
    # do something with @docB
    
    for my $aNode ($doc->getElementsByTagName('A')) {
      my @AB = $aNode->getElementsByTagName('B', 0);
      # do something with @AB
    }