in reply to Re: HOWTO XML::Simple
in thread HOWTO XML::Simple

The equivalent code in XML::Twig is below. Note that you could write very similar code with XML::LibXML (the difference being that you would use XPath to find the httpd elements and one (or more likely several!) DOM method(s) to add the attribute. If your initial file is big and you don't want to load it entirely in memory you can switch to using XML::Twig twig_handlers or twig_roots options, see the docs if necessary.

#!/usr/bin/perl -w use strict; use warnings; use XML::Twig; # keep_spaces is not completely necessary, it's just # there to keep the initial formating of the file my $twig= XML::Twig->new( keep_spaces => 1) ->parse( \*DATA) ; my $i=0; foreach my $httpd ( $twig->root->children( 'httpd')) { my $config= $httpd->text; # do something with $config $httpd->set_att( config => ++$i); } $twig->print; __DATA__ <file> <httpd><![CDATA[ ...1st piece of httpd configuration ]]></httpd> <not_httpd /> <httpd><![CDATA[ ...2nd piece of httpd configuration ]]></httpd> </file>