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

I have a XML file like this structure <DOC> <S Sid='1'> <REF ID='1' TYPE='ANAPHOR' EXT='NAME'>he</REF>is hardworking guy. </S> <S Sid='2'> <REF ID='2' TYPE='ANAPHOR' EXT='FAMILY'>he</REF> </S> </DOC> I would like to replace the REF element value (he) with EXT value (NAME) .Make consider the value of EXT and REF element are different and I have many REF element in my document .Please kindly help me.I do not know which perl module is suitable for my problem.Tx

Replies are listed 'Best First'.
Re: Search and Replace in XML
by toolic (Bishop) on Sep 14, 2009 at 15:21 UTC
    XML::Twig should be suitable for your problem. It will be well worth your time to work through the examples in the tutorial.

    In the future, it would be easier to understand your question if you posted your XML code inside 'code' tags. See Writeup Formatting Tips

      but having something like this:
      <DOC> <S Sid='1'> <REF ID='1' TYPE='ANAPHOR' EXT='NAME'>he</REF>is hardworking guy. </S> <S Sid='2'> <REF ID='2' TYPE='ANAPHOR' EXT='FAMILY'>he</REF> </S> </DOC>
      how can I replace the REF value with it's @EXT value using XML::TWIG and output as the same xml just replacing those for all documents? Thanks again for your clue.
        Set up a Twig handler to find all the REF elements. Parse the XML file. In the handler routine, get the text of the EXT attribute. Set the text of the REF element to be the text of the EXT attribute. Print out the modified XML.

        After you have written some code, if you are still having trouble, post your code along with the expected output.

Re: Search and Replace in XML
by Jenda (Abbot) on Sep 14, 2009 at 17:12 UTC

    Looks like a perfect task for XML::Rules in the filter mode. Create a new XML::Rules object with style => 'filter' and a custom rule for <REF> tags replacing the _content by the value of the EXT attribute and use the filter() or filterfile() method.

    Jenda
    Enoch was right!
    Enjoy the last years of Rome.

      seems easy using the rules. but never worked with XML::RULES, would it be simple to learn fast?

        Depends. If you are used to passing subroutine references around or to a declarative style of programming it should be a no-brainer. If you are set on the procedural thinking, it takes some brain rewiring. In this particular case the implementation really is simple. You load the module, you define the object with just a single custom rule that copies the $_[1]->{EXT} to $_[1]->{_content} and returns the $_[0] => $_[1] pair and then call the filter() or filterfile() method. It's all documented. Try and ask if you do not understand something or if something does something unexpected.

        Jenda
        Enoch was right!
        Enjoy the last years of Rome.