Ppeoc has asked for the wisdom of the Perl Monks concerning the following question:
Say I want to parse all the children in the snippet code below. I want to recursively parse each node till the last child is reached. I have no information about the nodes as they are dynamic. My actual file is highly nested. How can I do this using Twig?<?xml version="1.0" encoding="UTF-8"?> -<ArrayOfBooks> -<Book> <Title>The book of books</Title> <Author>Sally</Author> <Released>1/2/2008</Released> </Book> -<Book> <Title>The page of pages</Title> <Author>Amanda</Author> <Released>6/3/1998</Released> </Book> <Book> <Title>The book of pages</Title> <Author>John</Author> <Released>6/22/1963</Released> </Book> <Book> <Title>The rock of ages</Title> <Author>Frank</Author> <Released>5/21/2004</Released> </Book> <Book> <Title>The age of rocks</Title> <Author>Mary</Author> <Released>8/16/1944</Released> </Book> </ArrayOfBooks>
my $twig = XML::Twig->new( twig_handlers => { '/ArrayOfBooks/Book' => +\§} ); my $input ='Books.XML'; $twig->parsefile($input); sub sect { my ($twig, $ele) = @_; depth++ #if node does not contain children { end_element($ele); depth--; return; } #node contains children sec($ele); } sub end_element { # I need both key and value. eg Title: The page of pages my ($leaf) = @_; print $key; }
|
|---|