|laziness, impatience, and hubris|
Re: Module for XML outputby saberworks (Curate)
|on Jan 10, 2012 at 20:19 UTC||Need Help??|
I wrote this originally on blogs.perl.org: Using XML::Compile to output XSD compliant XML. It may help if you decide to make an XSD file.
As part of a recent project I was given an XSD file (xml schema definition) and asked to output compliant XML. CPAN to the rescue. I found XML::Compile::Schema which is a cool module that allowed me to do this with very little fuss. The documentation is really good but I think a tutorial-style post might be helpful.
To do this you’ll need to install XML::Compile and XML::LibXML.
You can use XML::Compile::Schema to read in your xsd file and output a perl hash template. Then you can use that example template to construct a hash of real data and then have XML::Compile::Schema output a valid XML file.
For this tutorial, download a sample .xsd file from here. Then write a perl script like so to dump a perl hash template.
The relevant output looks like this:
The comments are helpful (and were provided by XML::Compile::Schema directly, not by me). It basically says your data structure should start as a hashref which should contain an entry called “address” which is a reference to an array. This array should be a list of hash references which each contain two elements, name and street.
From this you can deduce that a valid hash will look something like this.
In order to output the XML, you have to do this:
My output looks like this:
The actual XSD and resulting XML files I was dealing with were much more complicated but I followed this process and had no trouble whatsoever.