0

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.

2 Answers 2

3

I wrote a tutorial on this a while ago: http://blogs.perl.org/users/brian_e_lozier/2011/10/using-xmlcompile-to-output-xsd-compliant-xml.html

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.