rpg
rpg

Reputation: 1652

Example Perl code for generating XML from XSD using XML::Compile

Can anybody please show me an example for generating XML from XSD using XML::Compile::Schema.

I am trying to post my script which I am trying along with the XSD but I am not able to do that. so I am looking for a any sample example.

Upvotes: 0

Views: 4566

Answers (2)

Jacob CUI
Jacob CUI

Reputation: 1345

In short words, you'll need to do:

  1. Convert the XSD format to Perl hash structure
  2. Construct this Hash, fill in the data
  3. Convert the Hash to XML

Packages required:

  • XML::Compile::Schema
  • XML::LibXML::Document

Following code create a Perl structure from XSD definition.

use XML::Compile::Schema;
use Data::Dumper;

my $filename = $ARGV[0] || "";

if(!$filename){
warn "Please provide the WSDL definition file.";
exit 10;
}

my $schema = XML::Compile::Schema->new($filename);
my $hash;

print Dumper $schema->template('PERL' => 'Application');

Then the Perl data structure created by this program looks like:

{
  MakeName =>
    {
     UniqueID => "anything",
     _ => "example", },

       MakeDetails =>
     {  
      Name =>
      {
       UniqueID => "anything",
       _ => "example", }, 
     },
   };

So the rest of your job will create the same structure in your program, fill in the content like:

  my $hash = {
    MakeName => {
      UniqueID => 'xxxx',
      _ => 'Name of the Make',
    },

    OtherFields => foo_bar_get_other_hash(),
   };
 ....

 ## breathtaking moment, create the XML from this $hash 

 my $schema = XML::Compile::Schema->new("/opt/data/your.xsd");

 my $doc = XML::LibXML::Document->new();
 my $writer = $schema->compile(WRITER => 'Application');

 my $xml;

 ## Create $xml in the memory based on the Schema and your $hash
 eval{ $xml = $writer->($doc, $hash);};   

 if($@){
# Useful if the format is invalid against the Schema definition
    # Or if there are other errors may occurs
    $err_msg = $@->{message}->toString();
return ("", $err_msg);
 }

 ## If you want save this $xml to file, convert it to string format first
 $doc->setDocumentElement($xml);
 my $ori_content = $doc->toString(1);
 ## Now $ori_content holds the full XML content.

Upvotes: 3

Related Questions