0

I would like to create a web form that would output xml. For example an input field would be First Name and the output would be fname

For doing this - what would the recommended approach be? I am open to anything and am willing to learn something new.

samsam
  • 1
  • 1
  • 1

2 Answers2

2

Do you want to produce XML right there from the form without submitting it, or from the back-end script processing the form data upon submissions?


For the first option (generate XML on the client side without submitting the form), you have to use JavaScript.

Since Perl is one of your tags, I assume this is NOT what you want to do and won't expand further.


For the second option (back-end script processing the form data upon submissions), you can use the following code structure.

use XML::Simple;
my %form_fields = process_form_data(); 
    # This depends on what framework you use, e.g. CGI.pm, TT, Embperl, etc...
    # Most Perl web frameworks already create a hash for you
    #      with keys being input element names
my %xml_hash = ();
foreach my $name (keys %form_fields) {
    next unless $process_form_field{$name}; # If only some are put into XML
    $xml_hash{$name} = $form_fields{name};  # Assuming no multiple values. 
}
# Loop over $xml_hash keys and find if any required ones are missing...
my $xml_string = XMLOut({root_element_name => \%form_fields});

It's an approximation (the exact answer is impossible since you didn't clarify any of the details, such as your Perl web framework, desired XML module, sample form data or XML structure); I assumed that a predefined set of form elements whose names are in %process_form_field hash get translated into XML elements with the same name all stored flatly under a <root_element_name> parent element, and that your Perl web framework has a method process_form_data() which translates from form data (QUERY_STRING or POST data) into a hash mapping form's input element names to submitted values (e.g. Embperl has a built-in %fdat hash that automatically achieves this). I further assume none of the elements submit >1 value for simplicity's sake.

Community
  • 1
  • 1
DVK
  • 126,886
  • 32
  • 213
  • 327
0

You could use XSLT templates. They'll help you keep your business logic and content (the XML) separate so that if your code changes in the future you just adjust the template without affecting your XML interface.

I'm assuming other applications will be dependent on your XML output and that you probably want to make sure it stays uniform and consistent.

XSLT can also work with multiple platforms, so if you ever move from Perl to some other language, you can take this with you.

jamesmortensen
  • 33,636
  • 11
  • 99
  • 120
  • 2
    How exactly can you translate **form data** using XSLT? (as opposed to generate the form's HTML from XML input)? – DVK Jan 02 '11 at 09:58