in reply to Re^2: XML::Twig Question
in thread XML::Twig Question

Your example code is close, just not quite there yet.
use strict; use XML::Twig; my $parser = new XML::Twig( twig_print_outside_roots => 1, twig_roots => { 'Title[@Name="Advanced Perl Programming"]' => sub { my ( $tree, $element ) = @_; $element->set_att( Name => 'Advanced Perl' ); $element->print; } } ); $parser->parse_file('books.xml');
Notice a couple of things I did differently:
- Put your twig_roots key in single quotes. Since you're using a '@' to select an element with an attribute, you don't want Perl to think you're trying to throw a variable name in there.
- Rather than specifying your twig_roots value as a 1, use either a reference to a sub or an anonymous sub as I did above. This gives you a lot more flexibility to do what you want. Inside this sub, is where we want to change the "Name" attribute.
- Specify twig_print_outside_roots so that it prints the rest of the document along with the twig_root you've specified

That should do what you were attempting.

--Brian

Replies are listed 'Best First'.
Re^4: XML::Twig Question
by ramya2005 (Scribe) on Aug 16, 2005 at 17:21 UTC
    Thank you! This code works.
Re^4: XML::Twig Question
by ramya2005 (Scribe) on Aug 16, 2005 at 19:36 UTC
    I tried to make use of the example code that you provided. It works! I am stuck when I try to enhance it to deal with two XML files. Please help!
    I have the following two XML files.

    books.xml
    <Books> <Titles Mode="List"> <Title Name="Programming Perl"/> <Title Name="Advanced Perl Programming"/> <Title Name="Learning Perl on Win32 Systems"/> </Titles> </Books>
    filter.xml
    <Filters> <Titles> <Title Name="Programming Perl"/> <Title Name="Advanced Perl Programming"/> <Title Name="Learning Perl on Win32 Systems"/> </Titles> </Filters>
    I am trying to do the following using the code below.
    1. Change the 'Title Name' in 'books.xml' by appending the existing 'Title Name' with some random number.
    2. Change the corresponding 'Title Name' in 'filter.xml' Now the problem is I am able to correctly parse the items. But at at the end when I print the 'books_tree - twig' only the Title name 'Learning Perl on Win32 Systems' reflects the changes. Everything else is same as the original books.xml file.

    Please tell me how to fix this?