0

I need to modify an XML document and dump it back. I am able to perform this using the XML::Parser in perl however I can't find a way to dump it back. Couldn't find much around writing it back..

one of the dumb implementation

use warnings;
use strict;
use XML::Parser;
use Data::Dumper;

sub char_handler
{
        my ($parser, $text) = @_;
        $text = #DO SOMETHING HERE WITH THE TEXT
}

my ($file) = @ARGV;
open(FILE,$file);
$xml=<FILE>;
my $parser = new XML::Parser( Style=>"Tree",
                              Handler => {
                              Char => \&char_handler
                });
my $doc = $parser->parse($xml);

print Data::Dumper->Dump([$doc]);

dumps the XML. 
Addy
  • 731
  • 5
  • 15
  • can't use Twig at the moment due to limitations with the environment and wanted to keep it simple. XML::Simple may be... but I have the same question with XML::Simple as well. – Addy Jun 25 '19 at 13:49
  • What about [XML::LibXML](http://p3rl.org/XML::LibXML)? – choroba Jun 25 '19 at 13:56
  • [Mojo::DOM](https://metacpan.org/pod/Mojo::DOM) or [Mojo::DOM58](https://metacpan.org/pod/Mojo::DOM58) are more options. [Don't use XML::Simple](https://stackoverflow.com/a/33273488/5848200). – Grinnz Jun 25 '19 at 16:22
  • I don't think you can use handler functions to modify the document being parsed like that. – Shawn Jun 25 '19 at 16:30
  • @Shawn you are right I just dumped the xml back and it was the same any other alternative with XML::Parser or is twig or others? – Addy Jun 25 '19 at 18:05
  • @choroba - not available I will have to get it worked out to be installed – Addy Jun 25 '19 at 18:06

1 Answers1

2

XML::Parser is just a parser it's not really intended for modifying a document and saving it back out as XML. For that type of application, you need module with some type of DOM (document object model) that preserves enough information about the document and has the ability to serialise back to XML.

I use and recommend XML::LibXML and have written a tutorial that you might find useful.

That's by no means the only option, but it is solid and reliable. It's also simpler and more consistent than XML::Simple (which I know enough about to say don't use it).

Grant McLean
  • 6,898
  • 1
  • 21
  • 37
  • Simple modifies the XML structure and it's confusing parser. I'd agree to that. Your tutorial is nicely written however is exhaustive as well :) would read it in more depth once I get more time – Addy Jun 27 '19 at 17:28