This is still in a fairly early stage of development, but take a look at the module XML::LibXML::Augment which I'm developing. (Not on CPAN yet I'm afraid.)
The idea is that XML::LibXML already provides a nice object-oriented view of the data, but we can specialise each object to make it even better. So say we have some XML:
<employees xmlns="http://megacorp.example/"> <person> <name>Alice</name> <salary>40000</salary> <bank_account number="10001234"/> </person> <person> <name>Bob</name> <salary>37500</salary> <bank_account number="10005678"/> </person> </employees>
Normally the two <person> elements would be XML::LibXML::Element objects. With XML::LibXML::Augment, we create a subclass of XML::LibXML::Element and bind it to the namespace-qualified name {http://megacorp.example/}person. And then whenever we hit a <person> element in our document, our subclass is automatically used.
So we might write:
{ package MegaCorp::Person; use XML::LibXML::Augment -names => ['{http://megacorp.example/}person']; sub get_salary { shift -> getElementsByTagName('salary') -> get_node(1) # not zero-indexed! -> textContent; } sub get_bank_account { shift -> getElementsByTagName('bank_account') -> get_node(1); } sub pay_salary { my $self = shift; my $acct = $self->get_bank_account; $acct->accept_funds($self->get_salary); } } { package MegaCorp::BankAccount; use XML::LibXML::Augment -names => ['{http://megacorp.example/}bank_account']; sub accept_funds { ... } } { package main; use XML::LibXML::Augment; my $doc = XML::LibXML->load_xml(location => 'emp.xml'); # Switch on augmentation for this document! XML::LibXML::Augment->upgrade($doc); my @employees = $doc->getElementsByTagName('person'); $_->pay_salary for @employees; }
If you think you'd like to give it a whirl, do get in touch with me! I'd love to have some extra people playing with it and reporting bugs and ideas for improvements.
In reply to Re: Create OO object from XML
by tobyink
in thread Create OO object from XML
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |