Search code examples
xmlperllibxml2xml-libxml

How to find child elements of a specified parent using XML::LibXML?


Suppose I have a XML file

<table>
    <person>
        <ID>1</ID>
        <Name>Adam</Name>
    </person>
    <student>
        <Subject>Math</Subject>
        <Marks>90</Marks>
    </student>
    <employee>
        <ID>7</ID>
        <Name>Bill</Name>
    </employee>
</table>

I want to get the child elements of the table element. i.e. the output should be person, student and employee. How do I do this with the XML::LibXML module in Perl?


Solution

  • for my $node ($doc->findnodes('/table/*')) {
        say $node->nodeName();
    }
    

    or

    use XML::LibXML qw( XML_ELEMENT_NODE );
    
    my $root = $doc->documentElement();
    for my $node ( grep { $_->nodeType() == XML_ELEMENT_NODE } $root->childNodes() ) {
        say $node->nodeName();
    }