#!/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 );