in reply to HOWTO XML::Simple

Seems like this will do the trick.. But be sure to check the caveats (e.g. ordering) in the XML::Simple for when not to use that module. Also, I came up with the code below by first making the DATA contain <httpd foo="bar"> and Data::Dumper'ing $conf to see what XML::Simple's data structure was.
use strict; use warnings; use XML::Simple; my $xs = XML::Simple->new(ForceArray=>['httpd']); my $s = do { local $/=undef; <DATA> }; my $conf = $xs->XMLin($s); my $ct = 0; foreach my $httpd ( @{$conf->{httpd}} ){ $ct++; if( ref($httpd) eq 'HASH' ){ $httpd->{number} = $ct; }else{ $httpd = { content=>$httpd, number=>$ct }; } } my $xml = $xs->XMLout($conf); print $xml; __DATA__ <x> <httpd><![CDATA[ ...1st piece of httpd configuration ]]></httpd> <httpd><![CDATA[ ...2nd piece of httpd configuration ]]></httpd> </x>

Replies are listed 'Best First'.
Re^2: HOWTO XML::Simple
by mirod (Canon) on Oct 21, 2005 at 12:27 UTC

    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>
Re^2: HOWTO XML::Simple
by pajout (Curate) on Oct 21, 2005 at 13:45 UTC
    Thanks, but, accidentally, Dumper($_) positioned in foreach body shows me variable with CDATA content only, the attribute is lost.
    I wish so simple thing, but I am not able to force XML::Simple to put both content and attribute of <httpd> element to some structure, which is an item of array @{$conf->{httpd}} :(
    Perhaps I am too tired or too dumb now, but my XML::Trivial is much more simple to use... I publish it after some real experiences, luckilly to avoid headache of some programmers similar to me.