Re: extracting nodes from nodes

Grant McLean <[email protected]> Thu, 09 May 2013 15:53:45 +1200
Newsgroups gmane.comp.lang.perl.xml
Message-ID <[email protected]>
On Tue, 2013-05-07 at 22:19 +0200, Anne Schumann wrote:

> using XML::XPATH, I extract rather big modes from a document. After
> that, is it possible to go on extracting subnodes from these by
> iterating over every node retrieved from the nodelist?

First up, I strongly recommend you switch from using XML::XPath to
XML::LibXML.  The XML::XPath module is abandoned, buggy and slow.  The
XML::LibXML module is much faster and has almost the same API so
switching should be straightforward.

With libxml, if you use an XPath expression to find a list of nodes, you
can use each node as the starting point for another XPath search, e.g.:

    foreach my $datacenter ( $doc->findnodes('//DataCenter') ) {

        foreach my $server ( $datacenter->findnodes('.//Server') ) {

            my $hostname = $server->findvalue('./@hostname');
            print "$hostname\n";

        }
    }

Given a DOM node, you can also simply iterate through all its immediate
children with code like:

    foreach my $node ( $datacenter->childNodes() ) {
        # your code here
    }

The documentation for methods available on all types of DOM nodes is
here:

    https://metacpan.org/module/XML::LibXML::Node

There are also pages for mode specific types of DOM nodes such as
Document, Element, Attr etc.


Regards
Grant


_______________________________________________
Perl-XML mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs