#!/usr/bin/env perl use strict; use warnings; use XML::Twig; my $twig = XML::Twig -> parse ( \*DATA ); if ( $twig -> get_xpath('/root/params/param[@name="this_setting"]') ) { print "Setting for \"this_setting\" already present\n"; } ## add another setting: my $add_to = $twig -> get_xpath ( '//params', 0 ); $add_to -> insert_new_elt ( 'last_child', 'param', { name => "another_setting" }, "Content here" ); $twig -> set_pretty_print("indented_a"); $twig -> print; __DATA__ #### Setting already present Content here #### #!/usr/bin/env perl use strict; use warnings; use XML::Twig; my $twig = XML::Twig->parsefile( 'your_file.xml' ); #search for "HostProperties" nodes within the tree. You can #be more specific about this if you need to. foreach my $HP ( $twig->get_xpath('//HostProperties') ) { #check if it has a "tag" element with a "mac-address" "name" attribute. if ( not $HP->get_xpath('./tag[@name="mac-address"]') ) { #insert a new element at the end of the entry. $HP->insert_new_elt( 'last_child', 'tag', { 'name' => 'mac-address' }, "DE:AD:BE:EF:F0:FF" ); } } #note - pretty printing helps reading, but might #cause some problems with certain XML constructs. Shouldn't in your specific example though. $twig->set_pretty_print("indented_a"); $twig->print; #to save it to a file: open ( my $output, '>', 'processed.xml' ) or die $!; print {$output} $twig -> sprint; close ( $output );