#!/usr/bin/perl use warnings; use strict; use feature qw{ say }; use XML::LibXML; for my $other_title ( '', 'old value', ) { my $xml = qq( $other_title ); my $dom = 'XML::LibXML'->load_xml(string => $xml); my ($other_title) = $dom->findnodes('//file/body/group/unit/alt-title/otherTitle'); if ($other_title->findnodes('text()')) { $other_title->removeChildNodes; } $other_title->appendText('new value'); print $dom; }