pradip patil
pradip patil

Reputation: 23

Update xml file in perl using XML::Simple or XML::Twig

Can someone please help me with this?

I want to modify the xml file using perl. I searched and found modules like XML::Simple/ XML::Twig but couldn't find an exact way.

Below is some part of my xml file. I want to modify value of Driver having name='sybase' and save this change to original file.

 <Properties>
    <Application>
        <Name>global</Name>
        <Cache>20</Cache>
        <Trace>true</Trace>
        <Drivers>
            <Driver name="sybase"> com.sybase</Driver>
            <Driver name="db2">com.db2</Driver>
        </Drivers>
    </Application>
</Properties>

Upvotes: 1

Views: 1289

Answers (1)

mirod
mirod

Reputation: 16136

One highly idiomatic way to do this would be this:

#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

XML::Twig->new( twig_handlers => 
                  { 'Driver[@name="sybase"]' 
                       => sub { $_->set_text( 'new driver')->flush }
                  },
                keep_spaces => 1, )
         ->parsefile_inplace( 'so.xml');

Beyond this, the usual way of "editing a file in place" is to process the file, output the result to a temporary file, then, if everything went OK, rename the temp file to the original file name.

Upvotes: 2

Related Questions