
At a high level, XML::Simple contains two main functions.
- XMLin - store XML in a variable
- XMLout - write an XML file
XMLout is almost always used after XMLin. In this example, XMLin is used to store <p>Hello World</p> in a variable named $xml and then XMLout is used to store the XML in a file named bar.xml.
#!/usr/bin/perl
use strict;
use warnings;
use XML::Simple;
my $xml= XMLin("<p>Hello World</p>");
XMLout($xml, OutputFile => "bar.xml");
In this example, bar.xml would contain something like this. Notice that the <p> tag is now <opt>. More on this in a moment.
<opt>Hello World</opt>
More commonly, an XML file is used. Let's say you have an XML file named foo.xml that contains the following.
<acme>
<name>Bugs Bunny</name>
</acme>
Here is how you would store the contents of foo.xml in a variable named $xml and then output to bar.xml.
#!/usr/bin/perl
use strict;
use warnings;
use XML::Simple;
my $xml= XMLin("foo.xml");
XMLout($xml, OutputFile => "bar.xml");
XMLDecl can be used to appended the XML declaration to line 1 of the output file.
XMLout($xml, OutputFile => "bar.xml", XMLDecl => "<?xml version='1.0' encoding='UTF-8' standalone='no'?>");
bar.xml should now contain something like this.
<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<acme>
<name>Bugs Bunny</name>
</acme>
If RootName is not used, often, the first and last tag in the output file will be opt.
<opt>
<name>Bugs Bunny</name>
</opt>
RootName can be used to declare the name of the first and last tag.
XMLout($xml, OutputFile => "bar.xml", XMLRoot => "<acme>");
Did you find this article helpful?
If so, consider buying me a coffee over at