FreeKB - Perl (Scripting) XML::Simple output XML (XMLout)
Perl (Scripting) - XML::Simple output XML (XMLout)

At a high level, XML::Simple contains two main functions.

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>");

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter 733a9 in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |