[VPM] converting objects to/from xml
Peter Scott
peter at PSDT.com
Mon Jul 14 15:48:13 CDT 2003
At 05:40 PM 7/12/2003 -0700, Darren Duncan wrote:
>I have another question, mainly for those of you who have worked with
>XML in Perl.
>
>Given that my SQL::ObjectModel objects are conceptually organized like
>XML, I would like to make a module which will convert them to XML, and
>conversely parse an XML document into one of those objects.
>
>I would like to use some suitable modules from CPAN which handle most
>of the work, but I am unsure of which ones to use. I had tried
>looking at some SAX modules (which seem common), because a callback
>interface seems to make sense for parsing XML, but I got the
>impression that this was perhaps too complicated. Most of the SAX
>examples I saw didn't have much to do with parsing or generating
>XML. I want object-oriented modules, and pure perl also, for the moment.
>
>I am wondering whether I would be better off coding this conversion
>myself, which I would expect is less than 40-100 lines of code, or
>whether the robustness or wider compatability brought by a CPAN module
>would be better.
>
>I prefer a simple solution, so I could for example do this:
>
>my $firstxml = "...";
>
>my $objectmodel = SQL::ObjectModel::XML->from_xml( $firstxml );
>
>my $secxml = SQL::ObjectModel::XML->to_xml( $objectmodel );
>
>Then "$firstxml eq $secxml" probably returns true.
>
>The hypothetical SQL::ObjectModel::XML module would have all the
>references to the CPAN module or alternately home grown implementation
>internally.
>
>Thanks in advance for any suggestions. -- Darren Duncan
O'Reilly's "Perl & XML" is excellent for this kind of thing. From
reading Chapter 6, I think you can do:
use XML::TreeBuilder;
my $tree = XML::TreeBuilder->new;
$tree->parse($firstxml);
my $objectmodel = SQL::ObjectModel->model_from_tree($tree);
Since I don't know what your object model is, I suggest you write the
method model_from_tree() to convert the XML::Parser tree to whatever
that is. That tree is a mixture of arrayrefs and hashrefs, too long to
type an example here. Logically it should map cleanly to your object
model. Obviously you can encapsulate all the calls above into a single
method of your own if you want.
Then for output you have:
my $secxml = SQL::ObjectModel->to_tree($objectmodel)->as_XML;
That last one is a bit harder because creating the tree requires making
this hierarchy of XML::Element objects. There are methods in that
class that let you build up such a tree.
Disclaimer: I haven't done this. But if I was going to do what you're
describing, this is the approach I would try to make work.
--
Peter Scott
Pacific Systems Design Technologies
http://www.perldebugged.com/
More information about the Victoria-pm
mailing list