in reply to Re: Outputting a hash as XML
in thread Outputting a hash as XML
To answer your question: it seems short-sighted to me. But not disallowed by the XML spec. XML explicitly allows ordering to matter (think of an XHTML doc - very important that the ndoes are in the right order), but for data transfer between programs, I'd not use it unless there are duplicate elements (e.g., more than one "model" tag).
As to solving it rather than griping about it, without a huge amount of thought applied here, the way I would likely approach this is to have an XML template file, say:
Then I would have XML::Twig load it, and then insert the data. I am not sure that there really is a generic solution here, so here's my offering using my favourite XML editor package ;-)<newPhone> <name></name> <description></description> <product></product> <model></model> </newPhone>
use strict; use XML::Twig; my $hash = { name => 'bob', product => 'blah', model => 'blah model', description => 'too much money? gimme!', }; my $twig = XML::Twig->new(pretty_print => 'indented'); ## mirod pointed out that I overlooked that parse can ## indeed handle file handles. Woops. :-) $twig->parse(\*DATA); my $elt = create_elements($twig->root(), $hash); $twig->print(); sub create_elements { my $parent = shift; my $data = shift; while (my ($k,$v) = each(%$data)) { # get_xpath returns a list. We should only every find 1 # node, so extract that. my @els = $parent->get_xpath($k); my $el = $els[0]; if ($el) { $el->set_text($v); } else { $el = XML::Twig::Elt($k => $v); $el->paste(last_child => $parent); } } } __END__ <newPhone> <name></name> <description></description> <product></product> <model></model> </newPhone>
Update: Simplified my parse call, thanks mirod!
|
|---|