Search code examples
xmlperlxml-parsing

Need to update xml tags which would be given as input to the perl script?


I am planning to write a script which would update XML tag value.

My requirement:

  1. tag value which has to be changed would be of user choice. It may be more than one at times.
  2. Script should throw an error if the user given tag does not exist in the XML.

The first challenge I am facing is: Which perl module to look out for? I have used XML::Twig to update a set of tags (How to print element names using XML::Twig) but there the XML tag names were hard coded in the script.

But my current requirement is to get the tag name and the value to be updated from user.

Regarding getting the input from user, I have an idea of creating a plain text file where user can give the tag name and its corresponding value. Script will parse the text file and pick the tag and its value accordingly. Is this a good idea or is there a better way to do it?

Can someone please give a heads up on this requirement.

It's a simple XML file which would be something like this:

<config>
  <tag1>alpha</tag1>
  <tag2>beta</tag2>
  <tag3>gamma</tag3>
</config>

(there might be many tags in similar fashion)

Let's say the user wants to update tag2 and he gives tag2 and its new value "beta is updated". Then the script should first check if tag2 exists, and if so, it should update the value.


Solution

  • First of all, your xml is not well-formed. I've fixed the closing tags. You should do it in your question too.

    You can solve this issue with XML::Twig module, using one of the arguments as a xpath expression:

    #!/usr/bin/env perl
    
    use warnings;
    use strict;
    use XML::Twig;
    
    XML::Twig->new(
        twig_handlers => {
            $ARGV[0] => sub {
                $_->set_text( $ARGV[1] );
            }   
        },  
        pretty_print => 'indented',
    )->parsefile( pop )->print;
    

    First argument is the tag to modify, second argument is the text to replace and the third one is the input file, so run it like:

    perl script.pl tag2 "beta is updated" xmlfile
    

    That yields:

    <config>
      <tag1>alpha</tag1>
      <tag2>beta is updated</tag2>
      <tag3>gamma</tag3>
    </config>