Bluesaka75 has asked for the wisdom of the Perl Monks concerning the following question:


Hi folks I need help for changing a password in an XML file like this:


This is my XML file

<Listens> <Listen name="SynchronousSSL"> <param name="Address" value="BLABLA1 /> <param name="Port" value="BLABLA2" /> <param name="ServerSocket" value="BLABLA3" /> <param name="SSLFlag" value="true" /> <param name="SSLTrustStoreFileName" value="BLABLA4" /> <param name="SSLTrustStorePassword" value="BLABLA5"/> <param name="SSLTrustStoreType" value="JKS" /> <param name="SSLKeyStoreFileName" value="BLABLA6" /> <param name="SSLKeyStorePassword" value="BLABLA7"/> <param name="SSLKeyStoreType" value="pkcs12" /> <param name="SSLClientCertificateMandatory" value="true" /> <param name="SSLDebug" value="false" /> </Listen>


and I wanted to change SSLKeyStorePassword with a new value "BLABLA8" for exemple.


So i will have

<Listens> <Listen name="SynchronousSSL"> <param name="Address" value="BLABLA1 /> <param name="Port" value="BLABLA2" /> <param name="ServerSocket" value="BLABLA3" /> <param name="SSLFlag" value="true" /> <param name="SSLTrustStoreFileName" value="BLABLA4" /> <param name="SSLTrustStorePassword" value="BLABLA5"/> <param name="SSLTrustStoreType" value="JKS" /> <param name="SSLKeyStoreFileName" value="BLABLA6" /> <param name="SSLKeyStorePassword" value="BLABLA8"/> <param name="SSLKeyStoreType" value="pkcs12" /> <param name="SSLClientCertificateMandatory" value="true" /> <param name="SSLDebug" value="false" /> </Listen>


How can i do this in perl?


Many thanks for the reply.

Discipulus added code tags

Replies are listed 'Best First'.
Re: XML replace password with a specific tag
by haukex (Archbishop) on Oct 13, 2022 at 20:39 UTC

    Here's one way with XML::LibXML:

    use warnings; use strict; use XML::LibXML; my $doc = XML::LibXML->load_xml(location => 'foo.xml'); my @nodes = $doc->findnodes('//param[@name="SSLKeyStorePassword"]'); if (@nodes) { warn "found more than one SSLKeyStorePassword" if @nodes>1; $nodes[0]->{value} = 'BLABLA8'; } else { die "did not find SSLKeyStorePassword" } $doc->toFile('bar.xml', 1);

    Whatever you do, do not use regular expresions.

      A bit shorter in XML::XSH2:
      open foo.xml ; set /Listens/Listen/param[@name="SSLKeyStorePassword"]/@value 'BLABLA8 +' ; save :b ;

      It sets the first such node, i.e. it doesn't warn if there are more than one, but it can be easily extended:

      my $l = /Listens/Listen/param[@name="SSLKeyStorePassword"] ; if (count($l) > 1) echo :e 'More than one node found' ; set $l/@value 'BLABLA8' ;

      map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]